1
votes

I am trying to copy tables from one word document to other word document one by one.

On running the Macro, the first table is copied to other document and then it is throwing following Error

Run-time error '5941' The requested member of the collection does not exist.

Below is my program

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

The error specified in the title occurs on this line of code:

  Set theTable = ActiveDocument.Tables(i).Range

Any Help Would Be Much Appreciated.

1
Looks like oTarget becomes the ActiveDocument, so on the second loop you're trying to copy a non-existent table from it, instead of from your original document.BigBen

1 Answers

2
votes

As mentioned in a comment, the problem is due to the use of Selection and ActiveDocument. For this reason, it's preferable to work with specific objects, rather than generalizations. If an object for each document is declared, and Ranges used instead of Selection, the code becomes more reliable and more understandable to anyone reading it.

Note: When transferring content between two Word documents (or places within a document) it's not necessary to use the Clipboard (copy/paste). Instead, Range.FormattedText can be used.

Note: I'm uncertain whether you really mean to open the same document for each iteration of the loop, since it's not being saved. The question also indicates that all tables should be copied to the same document. So I've moved opening the target document outside of the loop.

Note: You could also use For...Each to loop all the tables in a document, rather than using a counter.

Note: It's also very important to put Option Explicit at the top of a code module.

For example

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