How to Use VBA to Manipulate Word Tables
🔍 WiseChecker

How to Use VBA to Manipulate Word Tables

You have a Word document with tables that need repetitive formatting, data entry, or structural changes. Manually editing each table is slow and error-prone. Visual Basic for Applications (VBA) lets you automate these table tasks with code. This article explains how to write and run VBA macros to select, modify, format, and populate Word tables.

Key Takeaways: Automating Word Tables With VBA

  • Alt+F11 to open the VBA editor: This is the main workspace where you write and run macros for table manipulation.
  • Tables(Index) to reference a specific table: Use the index number or the ActiveDocument.Tables collection to target the correct table in your document.
  • Cell(Row, Column).Range.Text to read or write cell content: This property lets you get or set the text inside any table cell programmatically.

What VBA Can Do With Word Tables

VBA (Visual Basic for Applications) is the macro language built into Microsoft Office applications. In Word, VBA can access every object in a document, including tables, rows, cells, and their formatting properties. You can write a macro to apply consistent formatting across dozens of tables, extract data from cells into variables, or create new tables from scratch.

Before writing any VBA code, you need to enable the Developer tab in Word. Go to File > Options > Customize Ribbon and check the Developer box in the right panel. This tab gives you access to the VBA editor, macro recording, and macro security settings. You also need to set your macro security to enable all macros or digitally sign your code. Go to File > Options > Trust Center > Trust Center Settings > Macro Settings and choose Enable all macros.

Understanding the Word Object Model for Tables

The Word object model organizes tables in a hierarchy. The Document object contains a Tables collection. Each Table object contains a Rows collection and a Columns collection. Each Row contains Cells, and each Cell has a Range property that holds the text and formatting. You navigate this hierarchy using dot notation in VBA. For example, ActiveDocument.Tables(1).Cell(2, 3).Range.Text refers to the text in the third column of the second row of the first table in the active document.

Index numbers for tables, rows, and columns start at 1, not 0. This is different from many programming languages. Always verify which table is index 1 by checking the order tables appear in the document body. Tables inside nested structures like headers or text boxes are not included in the ActiveDocument.Tables collection.

Writing and Running a VBA Macro to Edit Word Tables

Follow these steps to create a macro that selects a table, changes its formatting, and updates cell content. The example macro will add a border to the first table, bold the header row, and insert a sum formula in the last column.

  1. Open the VBA Editor
    Press Alt+F11 in Word. The VBA editor opens in a separate window. If the Project Explorer is not visible, press Ctrl+R to show it.
  2. Insert a New Module
    In the Project Explorer, right-click Normal or your document name. Select Insert > Module. A blank code window appears.
  3. Write the Macro Code
    In the module window, type the following code:
    Sub FormatAndUpdateTable()
        Dim tbl As Table
        Dim r As Integer
        Dim c As Integer
        
        ' Reference the first table in the document
        Set tbl = ActiveDocument.Tables(1)
        
        ' Apply a solid border to the entire table
        With tbl.Borders
            .InsideLineStyle = wdLineStyleSingle
            .OutsideLineStyle = wdLineStyleSingle
            .InsideLineWidth = wdLineWidth050pt
            .OutsideLineWidth = wdLineWidth075pt
        End With
        
        ' Bold the first row (header row)
        For c = 1 To tbl.Columns.Count
            tbl.Cell(1, c).Range.Bold = True
        Next c
        
        ' Insert a sum formula in the last column, skipping the header
        For r = 2 To tbl.Rows.Count
            tbl.Cell(r, tbl.Columns.Count).Range.Text = "=SUM(LEFT)"
        Next r
        
        MsgBox "Table formatting and formulas applied."
    End Sub
  4. Run the Macro
    Place your cursor anywhere inside the macro code and press F5. Alternatively, close the editor, go to Developer > Macros, select FormatAndUpdateTable, and click Run.
  5. Save the Macro for Future Use
    To keep the macro available in all documents, save it in the Normal.dotm template. In the VBA editor, drag your module into Normal under Project Explorer. Save Normal.dotm when prompted.

Reading Data From a Table With VBA

To extract data from a table, loop through each cell and store the text in an array or write it to another document. The following macro copies all cell values from the first table into a new document as plain text, one line per cell.

Sub ExportTableToText()
    Dim tbl As Table
    Dim r As Integer
    Dim c As Integer
    Dim newDoc As Document
    
    Set tbl = ActiveDocument.Tables(1)
    Set newDoc = Documents.Add
    
    For r = 1 To tbl.Rows.Count
        For c = 1 To tbl.Columns.Count
            newDoc.Content.InsertAfter _
                tbl.Cell(r, c).Range.Text & vbCrLf
        Next c
    Next r
End Sub

This macro creates a new blank document and appends each cell’s text followed by a carriage return. The Range.Text property includes a cell marker character (ASCII 13 or 7) at the end. To remove it, use the VBA Replace function: Replace(tbl.Cell(r, c).Range.Text, vbCr, “”) or Chr(7).

Creating a New Table From Scratch

You can create a table entirely with VBA. The following macro adds a table with 5 rows and 3 columns at the cursor position, fills the header row with column names, and sets column widths.

Sub CreateNewTable()
    Dim tbl As Table
    Dim rng As Range
    
    Set rng = Selection.Range
    Set tbl = ActiveDocument.Tables.Add(rng, 5, 3)
    
    ' Set column widths
    tbl.Columns(1).Width = InchesToPoints(1.5)
    tbl.Columns(2).Width = InchesToPoints(2)
    tbl.Columns(3).Width = InchesToPoints(1.5)
    
    ' Fill header row
    tbl.Cell(1, 1).Range.Text = "Product"
    tbl.Cell(1, 2).Range.Text = "Quantity"
    tbl.Cell(1, 3).Range.Text = "Price"
    
    ' Apply header formatting
    For c = 1 To 3
        tbl.Cell(1, c).Range.Bold = True
        tbl.Cell(1, c).Shading.BackgroundPatternColor = wdColorGray25
    Next c
End Sub

Common VBA Table Mistakes and How to Avoid Them

Runtime Error 5941: The requested member of the collection does not exist

This error occurs when you reference a table index that does not exist. For example, ActiveDocument.Tables(2) fails if the document has only one table. Always check the Tables.Count property before accessing a specific index. Use an If statement: If ActiveDocument.Tables.Count >= 2 Then.

Cell Range Text Includes Extra Characters

The Range.Text property of a cell returns the visible text plus two hidden characters: a cell mark (ASCII 7) and an end-of-cell marker. When comparing or exporting cell values, strip these characters with the Replace function or use the following helper function:

Function CleanCellText(cell As Cell) As String
    Dim raw As String
    raw = cell.Range.Text
    ' Remove the last two characters (cell mark and end-of-cell mark)
    CleanCellText = Left(raw, Len(raw) - 2)
End Function

Macro Does Not Run on All Tables in the Document

If your macro only processes the first table, you are likely not looping through the Tables collection. Use a For Each loop to process every table:

Dim tbl As Table
For Each tbl In ActiveDocument.Tables
    ' Your code here
Next tbl

Table Borders Do Not Appear After Running Macro

The Borders property applies to the entire table object. If you set InsideLineStyle but not OutsideLineStyle, the outer borders may remain invisible. Always set both InsideLineStyle and OutsideLineStyle, and set the corresponding LineWidth properties. Use wdLineStyleSingle for a solid line.

VBA Methods for Table Manipulation: Manual vs Automated

Task Manual Method VBA Method
Add a row Right-click a row > Insert > Insert Rows Below tbl.Rows.Add or tbl.Rows(2).Select followed by Selection.InsertRowsBelow
Delete a column Select column > Right-click > Delete Columns tbl.Columns(3).Delete
Merge two cells Select cells > Layout tab > Merge Cells tbl.Cell(1,1).Merge tbl.Cell(1,2)
Set cell background color Select cell > Shading in Table Design tab tbl.Cell(2,1).Shading.BackgroundPatternColor = wdColorLightBlue
Sort table data Select table > Layout tab > Sort tbl.Sort ExcludeHeader:=True, FieldNumber:=1

VBA macros can perform these tasks on dozens of tables in seconds. Manual methods require repetitive clicking and are prone to human error.

You now know how to write VBA macros that select, format, read, and create Word tables. Start by recording a simple macro with Developer > Record Macro to see the generated code, then modify it to target specific table indexes and properties. For advanced tasks like merging cells conditionally or exporting table data to Excel, combine the table object with the Excel object model using early binding. Always test macros on a copy of your document first to prevent data loss.