【发布时间】:2021-09-02 12:56:23
【问题描述】:
我正在尝试将 doc1 的内容(格式化的文本和图像)复制到 doc2 中,其中 doc2 包含表格,并且我想将 doc1 的内容复制到 doc2 的第 18 个单元格中。
我从下面的参考中得到了代码,并相应地对其进行了修改。工作代码如下:
参考链接:How do I copy the contents of one word document to the end of another using vba?
Sub copyContents()
Dim wordWasRunning As Boolean
wordWasRunning = IsMSWordRunning()
Dim mswApp As Word.Application
Set mswApp = AttachToMSWordApplication()
Dim doc1 As Word.Document
Dim doc2 As Word.Document
Set doc1 = mswApp.Documents.Open("C:\Temp\SingleDoc.docx")
Set doc2 = mswApp.Documents.Open("C:\Temp\MergedDoc.docx")
Dim destination As Word.Range
Dim source As Word.Range
Set source = doc1.Content
Set destination = doc2.Content
destination.Tables(1).Range.Cells(18).Range.FormattedText = source
doc2.Close SaveChanges:=True
doc1.Close
If Not wordWasRunning Then
mswApp.Quit
End If
End Sub
当我使用不同的窗口并尝试将内容从 doc1 复制到 doc2(并且我从 doc3 运行宏)时,上面的代码正在工作。
问题: 我试图修改代码,以便可以从 doc2 本身运行宏。但是修改后的代码(如下所述)导致错误。
修改后的代码:
Sub copyContents()
Dim wordWasRunning As Boolean
wordWasRunning = IsMSWordRunning()
Dim mswApp As Word.Application
Set mswApp = AttachToMSWordApplication()
Dim doc1 As Word.Document
Set doc1 = mswApp.Documents.Open("C:\Temp\SingleDoc.docx")
Dim source As Word.Range
Set source = doc1.Content
ActiveDocument.Tables(1).Range.Cells(18).Range.FormattedText = source
End Sub
错误:
错误 5941:请求的集合成员不存在
*导致错误的行:ActiveDocument.Tables(1).Range.Cells(18).Range.FormattedText = source
我试图将上面的行更改为以下试验(只是为了使其与工作代码一样接近)但我得到了同样的错误(错误 5941)
试验一:
ActiveDocument.Content.Tables(1).Range.Cells(18).Range.FormattedText = source
试验 2:
ActiveDocument.Range.Tables(1).Range.Cells(18).Range.FormattedText = source
谁能帮我解决这个问题?
谢谢, 维奈
【问题讨论】:
-
嗨@PeterT,你能帮我解决这个问题吗..