Word Macro: Deleting Tables from a Selected Range

Sometimes I have to delete many tables from a Word document. It’s very annoying.
So, I’ve made this Word VBA macro.

This macro deletes all the tables from a selected range.

Macro Example

Sub DeleteTables_SelectedRange()

  Dim tbl As Table

  For Each tbl In Selection.Tables
    tbl.Delete
  Next tbl

End Sub

Description

Variable Declaration

Sub...

  Dim tbl As Table

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

The Table object represents a single table.

obj-Word-Table

Starts Looping

Sub...

  Dim tbl As Table

  For Each tbl In Selection.Tables

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

[Application.]Selection

The Application.Selection property returns the Selection object that represents a selected range.

obj-Word-Application-Selection

The Selection property is a member of the Word.Global class, so we can omit the Application property.

obj-Word-Global-Selection

Selection.Tables

The Selection.Tables property returns a Tables collection object in a selected range.

obj-Word-Selection-Tables

The Tables is a collection of a single Table objects.
So, the Tables collection object represents the tables in a specified range.

obj-Word-Tables

Delete the Table

Sub...

  Dim tbl As Table

  For Each tbl In Selection.Tables
    tbl.Delete

The 6th line deletes the table by the Table.Delete method.

obj-Word-Table-Delete

Loops Back

Sub...

  Dim tbl As Table

  For Each tbl In Selection.Tables
    tbl.Delete
  Next tbl

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

After every table is deleted from the active document, this macro ends.

Sub DeleteTables_SelectedRange()

  Dim tbl As Table

  For Each tbl In Selection.Tables
    tbl.Delete
  Next tbl

End Sub

Properties

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

Apply To

  • Word 2013
  • Word 2010
  • Word 2007