[VBA] How to Input Text into Specified Cells in Word Tables | Basic Syntax for Coordinate Control

目次

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

  1. Merged Cells: If the Word table has a complex structure (such as merged cells), the specified coordinates may become invalid.
  2. Overwriting: Range.Text overwrites the entire content of the cell. If you want to append text, use .InsertAfter instead.
  3. Multiple Tables: If there are multiple tables, change Tables(1) to Tables(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.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次