1
votes

I'm writing a set of macros to format a series of tables in a document. Part of this requires inserting a new row at the end of each table - however, when I try to do it using For Each <table> in ActiveDocument.Tables, it ends up inserting an infinite number of rows at the bottom of the first table. Both of these subs will enter an infinite loop:

Sub insertBottomRow1()
    Dim theTable As Table
    Dim theNewRow As Row
    For Each theTable In ActiveDocument.Tables
        Set theNewRow = theTable.Rows.Add
        'Other row formatting
    Next theTable
End Sub

Sub insertBottomRow2()
    Dim theTable As Table
    Dim theNewRow As Row
    For Each theTable In ActiveDocument.Tables
        theTable.Rows.Last.Select
        Selection.InsertRowsBelow
        Set theNewRow = theTable.Rows.Last
        'Other row formatting
    Next theTable
End Sub

I have a similar sub which uses the same structure to insert a row at the top of the tables, and this does not enter an infinite loop.

Sub insertTopRow()
    Dim theTable As Table
    Dim theNewRow As Row
    For Each theTable In ActiveDocument.Tables
        Set theNewRow = theTable.Rows.Add(theTable.Rows.First)
        'Other row formatting
    Next theTable
End Sub

I've done some experimentation (adding counters to the added rows, and stepping through the debugger), and the two subs that crash seem to be re-selecting the first table instead of moving onto the next table.

Any help would be appreciated. Thank you.

1

1 Answers

1
votes

I am not sure why your for each is going on forever, but you can easily just convert it to a normal for loop if you're having issues like so:

Sub insertTopRow()
    Dim theTable As Table
    Dim theNewRow As Row
    Dim i As Integer

    For i = 1 to ActiveDocument.Tables.Count
        Set theTable = ActiveDocument.Tables(i)
        Set theNewRow = theTable.Rows.Add(theTable.Rows.First)
        'Other row formatting
    Next i
End Sub

 Sub insertBottomRow()
    Dim theTable As Table
    Dim theNewRow As Row
    Dim i As Integer

    For i = 1 to ActiveDocument.Tables.Count
        Set theTable = ActiveDocument.Tables(i)
        Set theNewRow = theTable.Rows.Add
        'Other row formatting
    Next i
End Sub

You may also want to confirm it is an infinite loop, you can always break your executing code by pressing Ctrl + Pause/Break.

Another tip would be to combine these functions if the 'Other row formatting is the same for the top and bottom rows. You can just create a boolean parameter and have an if/else statement around the 'Set theNewRow =' line.