You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:55:50