简体   繁体   中英

Merge cells in table with ms word VBA macro

I want to merge in one cell with vba, but not working.

mycode :

Sub merge()
Dim x As Integer, i As Integer
x = ActiveDocument.Tables(1).Rows.Count
    With ActiveDocument.Tables(1)
      For i = 1 To x + 1
            If .Cell(i, 2).Range.Text = "" Then
            .Cell(Row:=i, Column:=2).merge _
            MergeTo:=.Cell(Row:=i, Column:=3)
            .Borders.Enable = False
            End If      
      Next i
    End With
End Sub

In the document, I have a table (five row and three columns).

For excel VBA code writers, it is a common conceptual problem, we used to treat a blank cell as empty (""). but actually an apparently blank Word table cell contains two invisible characters (at least in word 2007) ie chr(13) & Chr(7) . it could be tested with simple statement like

MsgBox Len(.Cell(1, 1).Range.Text)
MsgBox Asc(Right(.Cell(1, 1).Range.Text, 1))
MsgBox Asc(Left(.Cell(1, 1).Range.Text, 1))

so to make your code work it may be modified to something like

Sub merge()
Dim x As Integer, i As Integer, S As String
x = ActiveDocument.Tables(1).Rows.Count
    With ActiveDocument.Tables(1)
      For i = 1 To x
      S = .Cell(i, 2).Range.Text
      S = Replace(S, Chr(13), "")
      S = Replace(S, Chr(7), "")
            If S = "" Then
            .Cell(Row:=i, Column:=2).merge _
            MergeTo:=.Cell(Row:=i, Column:=3)
            .Borders.Enable = False
            End If
      Next i
    End With
End Sub

or test line may be modified to

If Len(.Cell(i, 2).Range.Text) = 2 Then

also could not understand why in your code you are iterating to ActiveDocument.Tables(1).Rows.Count+1 so for testing i used only For i = 1 To x

Try changing:

If .Cell(i, 2).Range.Text = "" Then

to:

If Split(.Cell(i, 2).Range.Text,vbCr)(0) = "" Then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM