Lee N
Lee N

Reputation: 1

Select all Tables & split in MS Word

I want my code to select all the tables of a MS word document and split all the rows but currently with this Macro, I am able to split the last table. Can anyone help me with modifying this code, It's not selecting the tables too now?

Following is the code:

Sub selecttables()
    Dim i As Integer    
    i = ActiveDocument.Tables.Count
    
    Set Tbl = ActiveDocument.Tables(i)
    
    Dim mytable As Table
    For Each mytable In ActiveDocument.Tables
        mytable.Range.Editors.Add wdEditorEveryone
    Next

    ActiveDocument.SelectAllEditableRanges (wdEditorEveryone)
    ActiveDocument.DeleteAllEditableRanges (wdEditorEveryone)
    
    For Each mytable In ActiveDocument.Tables
    Next

    Do While Tbl.Rows.Count > 1
        Tbl.Cell(2, 1).Range.Select
        Selection.InsertBreak Type:=wdColumnBreak '
        Set Tbl = ActiveDocument.Tables(ActiveDocument.Tables.Count)
    Loop
End Sub

Upvotes: 0

Views: 688

Answers (1)

freeflow
freeflow

Reputation: 4355

Your code is overly complicated for the task you wish to achieve. Having said that, the task itself is a tricky one.

When you split a Table you increase the number of tables in the document. For this reason you need to be careful that you are referencing the correct table. Thus, like many operations on collections in Office apps, you have to work backwards.

The code below should achieve your task (at least it works on my PC). The only caveat I would have is if there are vertically merged cells in your document as this code will split the merged cell but will leave the text in the first row of the merged sequence

Option Explicit

Sub SplitTables()
    
    Dim myTableCounter As Long
    For myTableCounter = ActiveDocument.StoryRanges(wdMainTextStory).Tables.Count To 1 Step -1
    
        SplitTableToRows myTableCounter
        
        
    Next
    
End Sub


Public Sub SplitTableToRows(ByVal ipTableIndex As Long)

    With ActiveDocument.StoryRanges(wdMainTextStory).Tables.Item(ipTableIndex)
    
        Dim myRowIndex As Long
        For myRowIndex = .Rows.Count To 2 Step -1
        
            .Cell(myRowIndex, 1).Range.Select
            Selection.SplitTable
            Selection.MoveUp
            

        Next
        
    End With

End Sub

Upvotes: 1

Related Questions