Background
In Excel, you can easily specify cells using addresses like “A1” or “F6,” but Word does not have this kind of cell notation.
I investigated how to input text at a specific coordinate position in a Word table. As a result, I found that you can easily insert text by specifying the “row” and “column” of the table using VBA.
Environment Used
- Application: Microsoft Word
- Technology: VBA (Visual Basic for Applications)
- Target: Tables inside Word
Implementation Code (VBA)
The following is the VBA code to input “mori” into the cell at the first row and first column of a Word table.
Sub InsertTextIntoTableCell()
Dim tbl As Table
' Word文書内の最初のテーブルを指定
Set tbl = ActiveDocument.Tables(1)
' テーブルのセル(1,1)に「mori」という文字列を入力
tbl.Cell(1, 1).Range.Text = "mori"
End Sub
When you run this code, the text “mori” is entered into the top-left cell (row 1, column 1) of the first table in the Word document.
Application: Inputting Text into Other Cells
For example, if you want to input text into the 2nd row and 3rd column, simply rewrite the code as follows:
tbl.Cell(2, 3).Range.Text = "sample"
Basic Syntax: You can manipulate cells using tbl.Cell(RowNumber, ColumnNumber).Range.Text = "Text".
Notes
- Merged Cells: If the Word table has a complex structure (such as merged cells), the specified coordinates may become invalid.
- Overwriting:
Range.Textoverwrites the entire content of the cell. If you want to append text, use.InsertAfterinstead. - Multiple Tables: If there are multiple tables, change
Tables(1)toTables(2)or another index to specify the target.
Summary
It is possible to manipulate cells in Word tables by specifying coordinates, just like in Excel.
By using the method introduced here, you can apply it to automated data entry and automatic report generation. This is a simple but practical technique, so please make use of it.
