Bharath Raj
Bharath Raj

Reputation: 33

How to automatically split cells in word table using VBA

In my Word document, I want to split 3rd column into 2 for each row in a table.

Sample Word Document

Sub ToonTable()
'
' ToonTable Macro
'
'

'*******Table Inputs************
    ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=15, NumColumns _
        :=3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
'********Create Table **************
    With Selection.Tables(1)
        If .Style <> "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        .ApplyStyleRowBands = True
        .ApplyStyleColumnBands = False
    End With
    'Split tird column Cell into two
    Dim i As Integer
    Dim x As Integer
    x = 0
    For i = 1 To 4
    x = x + 1
    ActiveDocument.Tables(1).Cell(x, 3).Range.Select
    Selection.Cells.Split NumRows:=2, NumColumns:=1, MergeBeforeSplit:=False
    Next i

    Selection.MoveDown Unit:=wdLine, Count:=1, Extend:=wdExtend

End Sub

Upvotes: 0

Views: 4241

Answers (1)

Tim Williams
Tim Williams

Reputation: 166196

When you merge each cell it changes the row index for the next cell down, so increment the row index by 2 each time:

Dim i As Long, x As Long
x = 1
For i = 1 To 4
    ActiveDocument.Tables(1).Cell(x, 3).Split NumRows:=2, NumColumns:=1
    x = x + 2 '<<<<
Next i

Upvotes: 3

Related Questions