smafeto
smafeto

Reputation: 23

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).

Upvotes: 2

Views: 7077

Answers (2)

macropod
macropod

Reputation: 13490

Try changing:

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

to:

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

Upvotes: 1

Ahmed AU
Ahmed AU

Reputation: 2777

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) i.e. 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

Upvotes: 1

Related Questions