Word Macro: Aligning All Tables to the Center in a Document

This Word VBA macro aligns to the center all tables in an active document.

Macro Example

Sub AlignAllTablesToCenter()

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables
    tbl.Rows.Alignment = wdAlignRowCenter
  Next tbl

End Sub

Description

Variable Declaration

The 3rd line declares an object variable named tbl represents a Table object.

Sub...

  Dim tbl As Table

The Table object represents a single table in a Word document.

obj-Word-Table

Starts Looping

The 5th line starts to loop through all the elements (=Table) of a collection (=Tables).

Sub...

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables

[Application.]ActiveDocument

  For Each tbl In ActiveDocument...

The [Application.]ActiveDocument property returns an active Document object.

obj-Word-Application-ActiveDocument

Because the ActiveDocument property is a member of the Word.Global class, we can omit the Application property.

obj-Word-ActiveDocument

ActiveDocument Tables (Document.Tables)

  For Each tbl In ActiveDocument.Tables

The ActiveDocument.Tables (Document.Tables property) returns the Tables collection object in the active document.

obj-Word-Document-Tables

The Tables is a collection of the Table object.
And the Tables collection object represents the tables in a selection, range, or document.

obj-Word-Tables

Centering Each Table

The 6th line aligns the table to the center in a page.

Sub...

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables
    tbl.Rows.Alignment = wdAlignRowCenter

Table.Rows

    tbl.Rows...

The tbl.Rows (Table.Rows property) returns the Rows collection that represents all the table rows within a table.

obj-Word-Table-Rows

Rows.Alignment

    tbl.Rows.Alignment = wdAlignRowCenter

The Rows.Alignment property returns or sets a WdRowAlignment constant that represents the alignment of the rows.

obj-Word-Rows-Alignment

The WdRowAlignment enumeration specifies alignment of rows.
That has these constants:

  • wdAlignRowCenter
  • wdAlignRowLeft
  • wdAlignRowRight

obj-Word-WdRowAlignment

Loops Back

The 7th line loops back to get the next table.

Sub...

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables
    tbl.Rows.Alignment = wdAlignRowCenter
  Next tbl

After every table is aligned to center, this macro ends.

Sub AlignAllTablesToCenter()

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables
    tbl.Rows.Alignment = wdAlignRowCenter
  Next tbl

End Sub

Properties

http://www.relief.jp/itnote/archives/word-vba-centering-tables.php

Apply To

  • Word 2013
  • Word 2010
  • Word 2007