Search code examples
vbams-wordword-2007

Copy Paste Table using Variable


I want to store a table in variable cTable and paste this whenever I need it with all formatting.

Sub copytable()
Dim cTable As TABLE

    Selection.Tables(1).Select

    cTable = Selection.Tables ' how do i assign table into variable

    Selection.MoveDown Unit:=wdLine, Count:=2

    Selection.Paste cTable ' how it going to be paste exacty the copied table

End Sub

Example is in table image :

@ken This is simple code of copy / paste table without variable

Selection.Tables(1).Select
Selection.COPY
Selection.MoveDown Unit:=wdLine, Count:=2
Selection.PasteAndFormat (wdPasteDefault)

Solution

  • It's not possible to store a table in a variable. It is possible to use a variable to reference a table, so that you can always refer back to it.

    This code sample demonstrates how it doesn't matter whether new tables are inserted before or after the table being referenced. If it was the first table in the document and it's copied to the beginning of the document, it can still be copied to the end of the document (or anywhere else).

    Sub ReuseTableReference()
        Dim doc As word.Document
        Dim tbl As word.Table
        Dim rngTableTarget As word.Range
    
        Set doc = ActiveDocument
        Set tbl = doc.Tables(1)
        Set rngTableTarget = doc.content
    
        'Copy the table to the beginning of the document
        rngTableTarget.Collapse wdCollapseStart
        rngTableTarget.FormattedText = tbl.Range.FormattedText
    
        'Copy the table to the end of the document
        rngTableTarget.Start = doc.content.End
        rngTableTarget.FormattedText = tbl.Range.FormattedText
    
        'Copy the table to the current selection
        Selection.FormattedText = tbl.Range.FormattedText
    End Sub
    

    Hard-coding in index value is often not desirable, of course. In that case, the table can be bookmarked so that you can pick it up from the bookmark, instead:

        Set tbl = doc.Bookmarks("tbl").Range.Tables(1)
    

    (Here, the index value 1 refers to the number of tables within the bookmarked Range.)