excelvbaword-table

VBA excel how to get table number in for each word table


i have Word template with 3 table with empty cells. After code have finished i check if there is empty cell in each table and if table contains empty cells then code delete that table, but if table have data then i need to insert text above that table. Each of that 3 table have they own specific text. So for word.document.tables(1) i need to put text "AAA", for word.document.tables(2) text "BBB"....

Problem is if i delete one table if is empty then that word document have 2 table and i need to delete table(3) so i get error that table(3) dont exist.

How can i get table count in for each loop?

Thanks!

Dim tbl As Table
For Each tbl In wDoc.Tables
            If Len(tbl.Cell(1, 1).Range.Text) = 2 Then
                tbl.Delete
            Else
                wDoc.tbl.Range.Collapse wdCollapseStart
                wDoc.tbl.Range.Move wdParagraph, -1
                    If wDoc.Tables(b) = 1 Then
                        wDoc.Tables(b).Range.InsertBefore "AAA"
                    ElseIf wDoc.Tables(b) = 2 Then
                        wDoc.Tables(b).Range.InsertBefore "BBB"
                    ElseIf wDoc.Tables(b) = 3 Then
                        wDoc.Tables(b).Range.InsertBefore "CCC"
                    End If
            End If
Next tbl

Solution

  • Loop from the end of the Tables collection using a For loop eg

    Dim tbl As Table, b As Long
    For b = wDoc.Tables.Count To 1 Step -1
        Set tbl = wDoc.Tables.Item(b)
    
        If Len(tbl.Cell(1, 1).Range.Text) = 2 Then
            tbl.Delete
        Else
            tbl.Range.Collapse wdCollapseStart
            tbl.Range.Move wdParagraph, -1
            If b = 1 Then
                tbl.Range.InsertBefore "AAA"
            ElseIf b = 2 Then
                tbl.Range.InsertBefore "BBB"
            ElseIf b = 3 Then
                tbl.Range.InsertBefore "CCC"
            End If
        End If
    Next b
    

    You then have the Table index number in b and the Table object in tbl