Word VBA: Adding a Row Above the Last Row of a Selected Table

This Word VBA macro adds a row above the last row of a selected table.

Macro Example

Sub AddRowAboveLastRow()

  With Selection.Tables(1)
    .Rows.Add BeforeRow:=.Rows.Last
  End With

End Sub

Description

Starts the With Statement

Sub...

  With Selection.Tables(1)

The 3rd line starts the With…End With statement.
This statement tells Word that following any actions apply to the Selection.Tables(1).

[Application.]Selection

  With Selection...

The [Application.]Selection property returns the Selection object that represents a selected range on a Word document.

obj-Word-Application-Selection

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

obj-Word-Global-Selection

Selection.Tables

  With Selection.Tables...

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

obj-Word-Selection-Tables

Tables(1) (Tables.Item(1))

  With Selection.Tables(1)...

The Tables.Item method returns an individual Table object in the Tables collection object. And the Tables.Item(1) represents the first table.

obj-Word-Tables-Item

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

Adds a Row

Sub...

  With Selection.Tables(1)
    .Rows.Add BeforeRow:=.Rows.Last

The 4th line adds a row above the last row of selected table.

Tables(1).Rows (Table.Rows)

  With Selection.Tables(1)
    .Rows...

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

obj-Word-Table-Rows

Adding a Row

  With Selection.Tables(1)
    .Rows.Add BeforeRow:=...

Rows.Add

We can add a new row before a row by the Rows.Add method with setting the parameter BeforeRow.

obj-Word-Rows-Add

  With Selection.Tables(1)
    .Rows.Add BeforeRow:=.Rows.Last

The Rows.Last property returns the last item in the Rows collection as a Row object. So, The 4th line adds a row above the last row.

End With

Sub...

  With Selection.Tables(1)
    .Rows.Add BeforeRow:=.Rows.Last
  End With

The 5th line ends the With…End With statement for the Selection.Tables(1) (Selection.Table).

Sub AddRowAboveLastRow()

  With Selection.Tables(1)
    .Rows.Add BeforeRow:=.Rows.Last
  End With

End Sub

Properties

http://www.relief.jp/itnote/archives/word-vba-adding-row-above-or-below-last-row.php

Apply To

  • Word 2013
  • Word 2010
  • Word 2007