合并多个表中的单元格Word

时间:2014-08-07 22:54:33

标签: vba merge ms-word word-vba

目前使用以下代码循环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,但一直在失败。

1 个答案:

答案 0 :(得分:0)

再看一遍后,意识到我错过了一个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