VBA, Word Table Insert/Remove Rows/Columns
In this article I will explain how you can add and delete rows and columns from tables in a word document using VBA.
Every word document has a Tables collection The first step in working with a table in VBA for word is to determine the table index. Tables in a word document start from the index “1” and go up. So for example the first table would be referenced by using the statement below:
Tables.Item(1)
The second table would be reference by using:
Tables.Item(2)
and so on . . .
All examples in this article will use the table below as their initial table:
Contents
Delete Row:
The code below will remove the second row of the first table:
Tables.Item(1).Rows(2).Delete
Result:
Delete Column:
The code below will remove the second column of the first table:
Tables.Item(1).Columns(2).Delete
Result:
Insert Row:
The codes below will all insert an empty row after the first row:
Tables.Item(1).Rows.Add (Tables.Item(1).Rows.Item(2))
Tables.Item(1).Rows(1).Select
Selection.InsertRowsBelow (1)
Tables.Item(1).Rows(2).Select
Selection.InsertRowsAbove (1)
The Rows.Add gets as input a row object. The new row will be inserted before the input row. The function Selection.InsertRowsBelow inserts as many rows passed as the input parameter below the currently selected row.
Result:
Insert Columns:
I find the column insertion methods a bit awkward. While there were 3 methods for inserting rows there are only 2 methods for inserting columns:
Tables.Item(1).Columns(1).Select
Selection.InsertColumnsRight
Tables.Item(1).Columns(2).Select
Selection.InsertColumns
The first method inserts a column to the right of the selected column. The second inserts a column to the left of the selected column.
You can download the file and code related to this article from the link below:
See also:
- Word VBA, Modify Table Data
- Word VBA Resize Table Columns and Rows
- Word VBA, Delete Empty Rows From Tables
- Inserting rows using Excel VBA
If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com
3 thoughts on “VBA, Word Table Insert/Remove Rows/Columns”