运行到错误462:通过Excel VBA使用WORD时,远程服务器机器不存在
我一直试图在Excel VBA中以编程方式打开一个Word文件,并使用书签在其中添加/编辑内容。 然而,我发现在交替运行时,我得到了'错误462:远程服务器不存在'的错误,我研究了很多,并且明白这有些事情要做'不合格的引用'。
然而,我不明白如何纠正下面的代码片段的合格的参考? 有人可以帮忙吗?
Set exR = ActiveSheet.Range(TestIdCol & CStr(DataRowNum) & ":" & TestIdCol & CStr(RowEnd)) ExistingEvidenceDoc = UseFileDialogOpen("Word Documents", "*.doc;*.docx") Set objWord = CreateObject("Word.Application") If ExistingEvidenceDoc <> "" Then Set objDoc = objWord.Documents.Open(ExistingEvidenceDoc) Else Exit Sub End If objWord.Visible = True Application.Wait Now() + TimeSerial(0, 0, 5) Set objSelection = objWord.Selection getExistingEvidences = ExistingTestEvidences(objDoc) o = DataRowNum For Each cell In exR If cell.Value <> "" And Not IsInArray(cell.Value, getExistingEvidences) Then objSelection.Style = ActiveDocument.Styles("Heading 1") objSelection.TypeText text:="Heading " + cell.Value objSelection.TypeParagraph objSelection.MoveLeft objSelection.HomeKey Unit:=wdLine objSelection.EndKey Unit:=wdLine, Extend:=wdExtend objDoc.Bookmarks.Add Name:="BMrk" + CStr(o), Range:=objSelection objSelection.Copy ActiveSheet.Range("Q" + CStr(o)).Select ActiveSheet.PasteSpecial Format:="Hyperlink", Link:=False, DisplayAsIcon _ :=False objSelection.MoveRight 'objSelection.Style = ActiveDocument.Styles("Paragraph") objSelection.TypeText text:=Range(DescriptionCol + CStr(cell.Row)).Value objSelection.TypeParagraph ElseIf IsInArray(cell.Value, getExistingEvidences) = False Then objSelection.EndKey objSelection.Style = ActiveDocument.Styles("Heading 1") objSelection.TypeText text:="Heading " + cell.Value objSelection.TypeParagraph objSelection.MoveLeft objSelection.HomeKey Unit:=wdLine objSelection.EndKey Unit:=wdLine, Extend:=wdExtend objDoc.Bookmarks.Add Name:="BMrk" + CStr(o), Range:=objSelection objSelection.Copy ActiveSheet.Range("Q" + CStr(o)).Select ActiveSheet.PasteSpecial Format:="Hyperlink", Link:=False, DisplayAsIcon _ :=False objSelection.MoveRight 'objSelection.Style = ActiveDocument.Styles("Paragraph") objSelection.TypeText text:=Range(DescriptionCol + CStr(cell.Row)).Value objSelection.TypeParagraph End If o = o + 1 Next cell MyErrorHandler: MsgBox "SeeHeadingPageNumber" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
另外,无论我定义的exR范围,它完成整个范围的执行,但最终MyErrorHandler被调用,我不明白为什么? 是有原因的吗?
请大家,帮助我…非常感谢您的帮助。 提前致谢
对Word对象有两个不合格的引用:
objSelection.Style = ActiveDocument.Styles("Heading 1")
出现两次,需要是:
objSelection.Style = objWord.ActiveDocument.Styles("Heading 1")
否则,您正在创build一个隐含的Word引用,您不能在您的代码中销毁。
您应该首先确保在任务pipe理器中没有oprhan winword.exe
。 杀死然后注销或注销来摆脱它们。
那么你应该添加类似这样的代码到最后的'explcitly'closures单词:
(我不确定确切的语法,希望你能解决这个问题)
IF Not(objWord Is Nothing) Then objWord.Close(False) Set objWord = Nothing End If
你应该添加类似于你的error handling程序的东西。
在开发和debugging过程中经常发生的情况是,有时单词不能正确closures,孤立的进程即使不可见,
你也可以使用
Set objWord = New Word.Application
代替
Set objWord = CreateObject("Word.Application")
因为这给你自动完成等
但是每个方面都有优势。