vba - VBA 运行时错误 5941 在 MS Word 中将多个表从一个文档一一复制到另一个文档
问题描述
我正在尝试将表格从一个word文档一张一张地复制到另一个word文档。
在运行宏时,第一个表被复制到其他文档,然后它抛出以下错误
运行时错误 '5941' 请求的集合成员不存在。
下面是我的程序
Sub copyTable()
Dim TotalTables As Integer
TotalTables = ActiveDocument.Tables.Count
i = 1
Do While (i < TotalTables)
Set theTable = ActiveDocument.Tables(i).Range
theTable.Select
Selection.Copy
Dim oTarget As Document
Set oTarget = Documents.Open("D:\Target.docx")
oTarget.Select
Selection.Collapse Direction:=wdCollapseStart
Selection.Paste
i = i + 1
Loop
End Sub
标题中指定的错误发生在这行代码上:
Set theTable = ActiveDocument.Tables(i).Range
任何帮助将非常感激。
解决方案
正如评论中提到的,问题是由于使用Selection
and ActiveDocument
。出于这个原因,最好使用特定的对象,而不是泛化。如果为每个文档声明一个对象,并Ranges
使用它来代替,那么代码对于阅读它的任何人来说都Selection
变得更加可靠和易于理解。
注意:在两个 Word 文档(或文档中的位置)之间传输内容时,无需使用剪贴板(复制/粘贴)。相反,Range.FormattedText
可以使用。
注意:我不确定您是否真的要为循环的每次迭代打开同一个文档,因为它没有被保存。该问题还表明应将所有表格复制到同一文档中。所以我已经在循环之外打开目标文档。
注意:您还可以使用For...Each
循环文档中的所有表格,而不是使用计数器。
Option Explicit
注意:放在代码模块的顶部也很重要。
例如
Sub copyTable()
Dim docTables as Word.Document
Dim docTarget as Word.Document
Dim theTable as Word.Table
Dim rngTarget as Word.Range
Dim TotalTables As Integer
Set docTables = ActiveDocument
TotalTables = docTables.Tables.Count
Set docTarget = Documents.Open("D:\Target.docx")
i = 1
Do While (i < TotalTables)
Set theTable = docTables.Tables(i)
Set rngTarget = docTarget.Content
rngTarget.Collapse Direction:=wdCollapseStart
rngTarget.Range.FormattedText = theTable.Range.FormattedText
i = i + 1
Loop
End Sub
推荐阅读
- cesium - 如何改变广告牌旋转的锚点?
- syntax - 无效的热键错误(可能的简单修复)
- discord - 如何将新成员的 ID 与数据库中的 ID 进行比较?
- python - 如何在 BeautifulSoup 中查找字符串
- python - 部分初始化的模块“turtle”没有属性“forward”(很可能是由于循环导入)
- flutter - 如何将文本与 RadioListTile 对齐
- javascript - 向 D3 添加工具提示功能
- windows - 组织 git repo 以避免遇到“文件名太长”问题
- vue.js - Axios 在 foreach 中存储相同的信息
- npm - VSC Apex-prettier-plugin-apex 未格式化 - 引发错误