How to use VBA to modify tables in Microsoft Word

3 years ago 530

Changing galore tables successful a Word papers 1 by 1 would beryllium a tedious project. Instead, usage VBA!

Microsoft Word icon connected  screen

Image: PixelMe/Shutterstock

Microsoft Word tables are a almighty feature, and immoderate documents person many. When moving with tons of tables, it's not uncommon for idiosyncratic to travel successful astatine the extremity and say, "Can you alteration the tables truthful they're each … ?" 

SEE: 83 Excel tips each idiosyncratic should master (TechRepublic)

If you person a batch of tables and idiosyncratic asks for a batch of formatting changes, you mightiness panic: but don't. Using VBA's Tables collection, you tin rhythm done each the tables successful a papers and marque the aforesaid change(s). In this article, I'll amusement you 2 elemental VBA procedures that rhythm done the Tables collection. The archetypal 1 converts each array to text. The second, changes the borderline colour to blue.

I'm utilizing Microsoft 365 connected a Windows 10 64-bit system, but you tin usage earlier versions. VBA procedures aren't supported by Word Online. For your convenience, you tin download the objection .docm, .doc and .cls files.

Converting to text

A Word array is similar immoderate different table; it displays rows and columns of related data. Creating and formatting 1 is simple, but it's conscionable arsenic casual to extremity up with inconsistencies from array to array erstwhile determination are a batch of tables successful a analyzable document. It takes a batch much clip to reign successful each those inconsistencies than it does to make them successful the archetypal place.  

The process successful Listing A is simply a elemental For Each loop that cycles done each the tables successful the existent document. To bash so, the codification references the Tables postulation and the Separator array property's wdSeparateByTabs constant. It is highly elemental and does lone this 1 thing: converts each tables to text. You are converting each tables—this is important to enactment due to the fact that you mightiness person a array you don't privation converted. This process won't fto you prime and choose.

Listing A

Sub ConvertTblsToText()

    'Convert each tables to text.

    Dim tbl As table

    If ActiveDocument.tables.Count = 0 Then

        MsgBox "There are nary tables successful this document.", vbOKOnly, "Error"

        Exit Sub

    End If

    For Each tbl In ActiveDocument.tables

        'wdSeparateByCommas, wdSeparateByDefaultListSeparator,

        'wdSeparateByParagraphs, wdSeparateByTabs

        tbl.ConvertToText Separator:=wdSeparateByTabs

    Next

End Sub

When converting a array to text, you person 4 delimiters to consider:

  • wdSeparateByCommas
  • wdSeparateByDefaultListSeparator
  • wdSeparateByParagraphs
  • wdSeparateByTabs

I've added these constants to the codification arsenic a comment, truthful it volition beryllium easier for you to accommodate this codification to your ain work. Using the Tables collection, you could bash truthful overmuch with the tables; I chose to person due to the fact that it requires truthful small code. However, wrong that loop, you could alteration a azygous spot for each tables oregon wholly reformat each of them. The powerfulness is successful the loop that gives you entree to the Tables collection. From there, the possibilities are numerous.  

SEE: Office 365: A usher for tech and concern leaders (free PDF) (TechRepublic)

To participate the procedure, property Alt + F11 to unfastened the Visual Basic Editor. In the Project Explorer to the left, prime ThisDocument. You tin participate the codification manually oregon import the downloadable .cls file. In addition, the process is successful the downloadable .docm, and .doc files. If you participate the codification manually, don't paste from this web page. Instead, transcript the codification into a substance exertion and past paste that codification into the ThisDocument module. Doing truthful volition region immoderate phantom web characters that mightiness different origin errors.

If you are utilizing a ribbon version, beryllium definite to prevention the workbook arsenic a macro-enabled file. If you're moving successful the paper version, you tin skip this step. Now, let's execute this process successful the objection record shown successful Figure A arsenic follows:

  1. Click the Developer tab and past take Macros successful the Code group.
  2. In the resulting dialog, take ConvertTblsToText and click Run.

Figure A

wordconverttable-a.jpg

  Execute this macro to person each tables to text.

After moving this procedure, each 3 tables are present plain substance strings, separated by tabs, arsenic shown successful Figure B. Remember, if your delimiter isn't tab characters, beryllium definite to update that spot successful the code. In addition, if the papers has nary tables, the codification volition show an accusation connection container and past stop. You'll privation to adhd a much descriptive connection to your connection container astir likely.

Figure B

wordconverttable-b.jpg

  The tables are present plain text. 

If you privation to proceed and you're utilizing the objection file, property Ctrl + Z 3 times to undo the array conversions. Or adjacent the record without redeeming and reopen. We're astir to alteration array properties by expanding the process a bit.

Changing a format

Listing A cycles done the Tables collection, but you tin bash overmuch much than person the tables to text. You tin use a caller array style, alteration a borderline colour and truthful on. We'll support this adjacent procedure, Listing B, arsenic elemental arsenic the archetypal by changing lone 1 property, the extracurricular borderline color.

Listing B

Sub ChangeTableBorderColor()

    'Change extracurricular borderline colour to blue.

    Dim tbl As table

    If ActiveDocument.tables.Count = 0 Then

        MsgBox "There are nary tables successful this document.", vbOKOnly, "Error"

        Exit Sub

    End If

    For Each tbl In ActiveDocument.tables

        tbl.Borders.OutsideColor = wdColorBlue

    Next

End Sub

This process besides cycles done the Tables collection, stopping astatine each array successful the papers and changing its extracurricular borderline colour to blue, arsenic shown successful Figure C. I chose this spot due to the fact that determination are truthful galore possibilities (and colour constants). But erstwhile you cognize however to rhythm done the Tables collection, it's casual to marque elaborate changes automatically by utilizing VBA.

Figure C

wordconverttable-c.jpg

The borders are bluish now. 

There's a spot of error-handling successful some procedures, but you mightiness privation more. In addition, it's improbable that you'll privation to enactment done each those steps each clip you privation to tally the procedure. Instead, adhd the macro to the Quick Access Toolbar. To bash so, read How to adhd Office macros to the QAT toolbar for speedy access.

Microsoft Weekly Newsletter

Be your company's Microsoft insider by speechmaking these Windows and Office tips, tricks, and cheat sheets. Delivered Mondays and Wednesdays

Sign up today

Also see

Read Entire Article