Working with Word.Tables

Sometimes you need to work with the table from within the code.
So how do you get the table?
How do you add rows?
…?

For this example we have the table in an bookmark. Now lets see how you can get the table from the bookmark.

Public Function GetTableInBM(ByRef Doc As Word.Document, _
                             ByVal BMName As String) As Word.Table
    Dim tbl As Word.Table
    
    With Doc
        If .Bookmarks.Exists(BMName) Then
            .Bookmarks(BMName).Select
            Set tbl = Selection.Tables(1)
        Else
            Set tbl = Nothing
        End If
    End With
    
    Set GetTableInBM = tblReturn
    
End Function

We now toke the table from the selection but this way you can get more from the bookmark. Try it!



Now that we have the table let add some data from our record set. Remember its only an example.

With tbl
    If .Rows.Count > 1 Then
        ' In this sample we will always add min 2 rows.
        ' If the counter is bigger then one we know that the last line is not empty
        ' that's why we have to add a new line.
        .Rows.Add
    End If
    ' Add  descr.
    .Cell(.Rows.Count, 1).Range.Text = NZ(rcs.Fields("Descr"), "")
    
    ' Add more info
    For intI = 1 To rcsData.RecordCount
        .Rows.Add
        .Cell(.Rows.Count, 1).Range.Text = NZ(rcs.Fields("Data1"), "")
        .Cell(.Rows.Count, 2).Range.Text = NZ(rcs.Fields("Data2"), "")
    Next
End With

HTH

Leave a Reply