vbams-word

Using VBA to loop through tables and move each to a separate page


I have set of separate tables in a word document. The number of tables will vary.

In the beginning state, the tables are separated from each other by a space, i.e. tightly packed. I want each table to be moved to the top of a separate page, i.e. as many pages as there are tables.

I have tried to copy what was suggested to this fellow:

Word vba jump to next page

By using the below:

     Sub format_tables()
     
     'Define variables
     
         Dim i As Integer
         Dim MyTable As Table
         Dim fileName As String

    'Loop through tables and move each sucessive table to next page
     
         For i = 1 To ActiveDocument.Tables.Count
         
             Set MyTable = ActiveDocument.Tables(i)
             MyTable.InsertAfter ChrW(12)
             
         Next i
     End Sub

With no success.

Do you have any ideas on how to solve this problem?


Solution

  • This works for me on Office 2010;

    Sub Test()
         Dim i As Integer
    
         For i = 1 To ActiveDocument.Tables.Count
            ActiveDocument.Tables(i).Range.InsertBreak Type:=wdPageBreak
         Next
     End Sub
    

    Note: You may use "ThisDocument" instead of "ActiveDocument" if you want to make sure this code to run on the document housing the code.