I created a VBA script to automatically assign names to a schedule table created in Word. This code automates the repetitive task of manually typing the same names over and over again.
目次
What I Want to Achieve
- Automatically list names in the “Person in Charge” column (Column 2) of a Word table.
- Start the list based on the name already entered in the second row (e.g., Row 2, Column 2).
- When the list reaches the end, it should loop back to the beginning.
Table Structure Image
| Date | Person |
| Nov 27 | Mori |
| Dec 1 | |
| Dec 11 | |
| … |
In a table like this, the script will automatically fill in the names starting after “Mori”.
VBA Code
Sub PopulateNamesInTableKeepingSecondCellName()
Dim doc As Document
Set doc = ActiveDocument
Dim tbl As Table
Set tbl = doc.Tables(1) ' Target the first table
' Define the name list
Dim names As Variant
names = Array("Mori", "Komori", "Nakamori", "Omori", "Hayashi", "Kobayashi", "Nakabayashi", "Obayashi")
' Get the name from Row 2, Column 2 (Remove end-of-cell characters)
Dim currentName As String
currentName = Trim(Left(tbl.Cell(2, 2).Range.Text, Len(tbl.Cell(2, 2).Range.Text) - 2))
' Find the index of the current name
Dim startIndex As Integer
startIndex = -1
Dim i As Integer
For i = LBound(names) To UBound(names)
If names(i) = currentName Then
startIndex = (i + 1) Mod (UBound(names) + 1)
Exit For
End If
Next i
' Insert names sequentially starting from Row 3
If startIndex <> -1 Then
For i = 3 To tbl.Rows.Count
tbl.Cell(i, 2).Range.Text = names(startIndex)
startIndex = (startIndex + 1) Mod (UBound(names) + 1)
Next i
Else
MsgBox "The name in Row 2, Column 2 does not exist in the list."
End If
End Sub
(Note: I updated the Japanese names in the array to English for this example code.)
Key Points
tbl.Cell(2, 2): The script uses the 2nd row, 2nd column as the starting reference point.- Cleaning Text: Word table cells contain special characters at the end (Line Break + Bell). The code uses
Left(..., Len(...) - 2)to remove these and get just the text. ModOperator: This is used to calculate the next index. It allows the script to loop back to the start of the list seamlessly when it reaches the end.
Execution Flow
- Enter a starting name (e.g., “Mori”) in the 2nd row, 2nd column of your Word table.
- Run the macro.
- The script inserts the subsequent names (e.g., “Komori”, “Nakamori”…) into the 2nd column starting from the 3rd row.
- If the rows exceed the number of names, it automatically loops back to the first name.
Summary
Using Word VBA allows you to efficiently create repeating tables for schedules or assignments.
- You just need to define the staff list as an array beforehand.
- It automatically updates only the 2nd column while keeping the table structure intact.
- It is perfect for creating duty rosters or rotation tables.
This snippet is very useful for improving business efficiency for anyone who routinely types the same names repeatedly.
