当前使用以下代码在Word中循环遍历表格并合并第一列中值相同的单元格:
Dim tbl As Word.Table
Dim cel1 As Word.Cell
Dim cel2 As Word.Cell
Dim rowIndex As Long, colIndex As Long, i As Long, r As Long
Set tbl = ActiveDocument.Tables(1)
colIndex = tbl.Columns.Count
rowIndex = tbl.Rows.Count
For r = 1 To rowIndex - 1
On Error Resume Next
Set cel1 = tbl.Cell(r, 1)
Set cel2 = tbl.Cell(r + 1, 1)
If cel1.Range.Text = cel2.Range.Text Then
cel2.Range.Text = ""
cel1.Merge MergeTo:=cel2
'r = r + 1
End If
Next r
当文档中只有一个表时,这很有效;然而,当有多个表时,什么都不会发生。我试过加一个With,但总是失败。
再看一遍之后,我意识到我遗漏了一个With语句。修改后的代码工作如下:
Sub MergeTest()
Dim tbl As Word.Table
Dim cel1 As Word.Cell
Dim cel2 As Word.Cell
Dim rowIndex As Long, colIndex As Long, i As Long, r As Long
Set tbl = ActiveDocument.Tables(1)
colIndex = tbl.Columns.Count
rowIndex = tbl.Rows.Count
For Each tbl In ActiveDocument.Tables
For r = 1 To rowIndex - 1
On Error Resume Next
Set cel1 = tbl.Cell(r, 1)
Set cel2 = tbl.Cell(r + 1, 1)
If cel1.Range.Text = cel2.Range.Text Then
cel2.Range.Text = ""
cel1.Merge MergeTo:=cel2
'r = r + 1
End If
Next r
Next
End Sub