Tuesday 25 September 2018

Word - Copying All Tables to a New Document

Tables are a great way to present many types of information. In fact, I've seen some documents that consist almost entirely of tables. If you do a lot of work with tables, you may (at some point) want to copy all the tables from one document to a brand new document. This could be helpful if you have tabular information that needs to be available in the new document, but you don't need the rest of the information from the original document.
The easiest way to do this type of copying is by using a macro. Fortunately, all the tables in a document are made available to VBA through the Tables collection. That means you can step through each item in the collection (each item will be an individual table) and then copy it.
Sub CopyTables()
    Dim Source As Document
    Dim Target As Document
    Dim tbl As Table
    Dim tr As Range

    Set Source = ActiveDocument
    Set Target = Documents.Add

    For Each tbl In Source.Tables
        Set tr = Target.Range
        tr.Collapse wdCollapseEnd
        tr.FormattedText = tbl.Range.FormattedText
        tr.Collapse wdCollapseEnd
        tr.Text = vbCrLf
    Next
End Sub
The macro, once run, creates a brand new document (Target) and copies the tables from the original document (Source) into the new one. (The source document is whatever document was active when you ran the macro.) The macro places a blank line between each table in the Target document. If you don't want the blank line, then remove or comment out the line just before the Next statement.

No comments:

Post a Comment