我正在开发一个实用程序来查找和更新 Word 中的 DOC 变量。我有一段代码可以循环遍历文档并显示带有变量名称的消息框,但是当它尝试打开下一个文档时收到错误。错误是:
System.Runtime.InteropServices.COMException:“RPC 服务器不可用。 (HRESULT 异常:0x800706BA)
我很困惑,因为我的代码无法访问任何网络。我认为可能发生的情况是文档关闭时 Word 也关闭,但我找不到解决方案来阻止这种情况。
我尝试过的其他事情:
- 确认UAC已禁用
- 确认 RPC 服务正在运行
-
已确认 RPC 和 DCOM 的注册表值正确
Private Sub LoopTemp()
Dim oDir As New DirectoryInfo(dPath)
Dim oFileArr As FileInfo() = oDir.GetFiles()
Dim oFile As FileInfo
Dim oVar As Variable
Dim oDoc = New Document()
Dim oWord As Application
oWord = CreateObject("Word.Application")
oWord.Visible = False
For Each oFile In oFileArr
oDoc = oWord.Documents.Open(oFile.FullName)
For Each oVar In oDoc.Variables
MsgBox(oVar.Name)
Next
oDoc.Close(SaveChanges:=WdSaveOptions.wdSaveChanges)
Next
oWord.Quit()
End Sub
当指向 COM 对象的“指针”在代码尝试重新使用它之前未从内存中正确释放时,就会出现 RPC 错误。从应用程序本身外部自动化 Office 应用程序时,这是一个很常见的问题。尤其是在使用 .NET 进行工作时,必须格外小心。
另一个需要注意的非常重要的事情是New
关键字不得与任何 Office 对象一起使用except Application
。尽管 API 允许,但切勿使用New Document
使用 Word,因为这会创建一个Document
无法正确释放的对象。
出于效率考虑,启动Word应用程序once应该足够了 - 只要正确释放它使用的 COM 对象(设置为Nothing
和垃圾收集)。
我将在问题中编写代码如下:
Private Sub LoopTemp()
Dim oDir As New DirectoryInfo(dPath)
Dim oFileArr As FileInfo() = oDir.GetFiles()
Dim oFile As FileInfo
Dim oVar As Variable = Nothing
Dim oWord As Application = NOthing
Dim oDoc As Document = Nothing
oWord = New Word.Application
oWord.Visible = False
For Each oFile In oFileArr
oDoc = oWord.Documents.Open(oFile.FullName)
For Each oVar In oDoc.Variables
MsgBox(oVar.Name)
Next
oVar = Nothing
oDoc.Close(SaveChanges:=WdSaveOptions.wdSaveChanges)
oDoc = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
Next
oWord.Quit()
oWord = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)