如何使用VBA自动拆分word表中的单元格

时间:2016-04-07 05:33:24

标签: vba ms-word word-vba

在我的Word文档中,我想将第3列拆分为表格中的每一行。

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

1 个答案:

答案 0 :(得分:3)

合并每个单元格时,它会更改下一个单元格的行索引,因此每次将行索引增加2:

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