VBA跨模块调用已打开Word文档报错,求最优解决方案
Word VBA 无法引用已打开的主文档
我需要在Word文档中编写内容,必要时在另一个文档撰写段落,关闭该文档后,将段落复制到始终处于打开状态的第一个文档中,但尝试多种方法均失败:
尝试的方法及报错
方法1
执行以下代码:
Dim wdDocMain As Word.Document Set wdDocMain = ActiveDocument
收到运行时错误4248:该命令不可用,因为没有打开的文档。
方法2
执行以下代码:
Dim wdDocMain As Word.Document Set wdDocMain = wdApp.Documents.Open(FileName:=pathmaindoc, ReadOnly:=False, Visible:=True) wdDocMain.Activate
收到运行时错误91:对象变量或With块变量未设置。
临时非最优解决方案
关闭已打开的文档后重新打开,代码如下:
Set wdDocMain = wdApp.Documents.Open(FileName:=pathmaindoc, ReadOnly:=False, Visible:=True)
补充代码片段
主过程代码
Dim wdapp As Word.Application Dim wdDoc As Word.Document Set wdapp = New Word.Application Set wdDoc = wdapp.Documents.Open(FileName:=PathName_HiveDown_Creation, ReadOnly:=False, Visible:=True) wdapp.Visible = True
调用模块的代码
当满足特定条件时,调用模块copyparafromtemplatetomain:
pathmaindoc = PathName_HiveDown_Creation pathtemplatedoc = PathName_Template 'wdDoc.Close savechanges:=True copyparafromtemplatetomain
模块代码
Public wdapp As Word.Application Public wdDocMain As Word.Document Sub copyparafromtemplatetomain(pathmaindoc As Variant, pathtemplatedoc As Variant, paramain As Variant, paratemplate As Variant, index As Integer) Dim wdDocTemplate As Word.Document Dim PathName_MainDoc As Variant PathName_MainDoc = pathmaindoc Set wdDocMain = wdapp.ActiveDocument
此处收到运行时错误91,仅关闭主过程中的文档后代码才能运行。
内容的提问来源于stack exchange,提问作者Yannis
相关产品推荐
相关产品推荐

