首页 > 解决方案 > 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

任何帮助将非常感激。

标签: vbams-word

解决方案


正如评论中提到的,问题是由于使用Selectionand 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

推荐阅读