【问题标题】:VBA Runtime Error 5941 on Copying Multiple Tables from one document to other one by one in MS WordVBA 运行时错误 5941 在 MS Word 中将多个表从一个文档一个一个文档复制到另一个文档
【发布时间】:2020-02-26 13:49:26
【问题描述】:

我正在尝试将表格从一个 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

任何帮助将不胜感激。

【问题讨论】:

  • 看起来oTarget 变成了ActiveDocument,所以在第二个循环中,您尝试从中复制一个不存在的表格,而不是从您的原始文档中复制。

标签: vba ms-word


【解决方案1】:

正如评论中提到的,问题是由于使用了SelectionActiveDocument。出于这个原因,最好使用特定的对象,而不是泛化。如果为每个文档声明一个对象,并使用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

【讨论】:

  • 谢谢@cindy-meister。我试过你的代码,但它显示错误“编译错误 - 找不到方法或数据成员”。错误在rngTarget.Range.FormattedText = theTable.Range.FormattedText 线上,在 rngTarget.Range.FormattedText 部分
  • @Dhruva 我不是 word-vba 专家,但我认为您需要删除 Range:rngTarget.FormattedText = theTable.Range.FormattedText
猜你喜欢
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多