Word VBA: Deleting Columns from All Tables in an Active Document

This Word VBA macro deletes the 2nd column from all the tables in an active document.

Macro Example

Sub Delete2ndRows()

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables
    tbl.Columns(2).Delete
  tbl

End Sub

Description

Variable Declaration

Sub...

  Dim tbl As Table

The 3rd line declares an object variable named tbl that will refer to a Table object.

Starts Looping

Sub...

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables

The 5th line starts to loop through all the elements (Table) of a collection (Document.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

Deleting the 2nd Column from Each Table

Sub...

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables
    tbl.Columns(2).Delete

The 6th line deletes the 2nd column from each table.

Table.Columns

    tbl.Columns...

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

obj-Word-Table-Colmuns

Columns(2) (Columns.Item(2))

    tbl.Columns(2)...

The Columns.Item method returns an individual Column object in the Columns collection object. And the Columns.Item(2) represents the second column.

obj-Word-Colmuns-Item

The Item method is a default member of the Columns collection object. We can see a little blue marble beside its icon in the Object Browser. So we can omit the .Item.

Columns(2).Delete (Column.Delete)

    tbl.Columns(2).Delete

The Columns(2).Delete (Column.Delete method) deletes the column.

obj-Word-Colmun-Delete

Loops Back

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

Sub...

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables
    tbl.Columns(2).Delete
  Next tbl

After every table is evaluated, this macro ends.

Sub Delete2ndRows()

  Dim tbl As Table

  For Each tbl In ActiveDocument.Tables
    tbl.Columns(2).Delete
  tbl

End Sub

Properties

http://www.relief.jp/itnote/archives/word-vba-delete-column-from-tables.php

Apply To

  • Word 2013
  • Word 2010
  • Word 2007