打开word后,不能进行操作。
本来在word中使用vba编写,后来由于需要关闭word程序,所以将代码移到vb6中。
问题:循环第一次时,一切正常,文档可以打开、可以移动光标、输入文字、也能正常保存退出;
循环第二次时,问题就出现了,位置在 Selection.TypeText "Hello",不能移动光标、也不能输入文字。错误提示为:
Run-time error '462':
The remote server machine does not exist or is unavailable.
代码如下:
Sub test()
Dim mWord As New Word.Application
Dim doc As Word.Document
Dim i As Long
'以下代码循环3次
For i = 1 To 3
'打开文档
Set mWord = CreateObject("word.application")
mWord.Visible = True
Set doc = mWord.Documents.Open("C:\Doc1.doc")
doc.Activate
Selection.TypeText "Hello" '运行此语句出错
'保存关闭文档
doc.Save
doc.Close
Application.Quit
Set doc = Nothing
Set mWord = Nothing
Next
End Sub
[解决办法]
Sub test()
Dim appWD As Word.Application
Dim doc As Word.Document
Dim i As Long
'以下代?循?3次
For i = 1 To 3
'打?文?
Set mWord = CreateObject("word.application")
mWord.Visible = True
Set doc = mWord.Documents.Open("D:\111.docx")
'Doc.Activate
'Selection.TypeText Text = "Hello"
doc.ActiveWindow.Selection.TypeText ("HELLO")
'保存??文?
doc.Save
doc.Close
mWord.Quit
Set doc = Nothing
Set mWord = Nothing
Next
End Sub