0
votes

I am trying to insert tables marked with a Name via a bookmark so I can later recognize them again.

Below I have added my source code in question. At pos3 I created a table with 2 rows and add a bookmark for its range. But when repeating the Sub I always end up in the case of pos1 .. my bookmark is not found in the table selection. (trying to reach pos2)

The bookmark itself is added, but maybe not to the table. I suspect the error to be there.

I can see the bookmark in the bookmark-list of Word. But if I do a manual "go to" the cursor seems to end up off screen somewhere, so I suspect its not added correctly to the table range.

Private Sub PrepareFooter()
Dim oSection As Section
Dim oFooter As HeaderFooter
Dim oRng As Range
Dim tbl As Table
Dim cell As cell
Dim foundFooterTable As Boolean
For Each oSection In ActiveDocument.Sections
    For Each oFooter In oSection.Footers
        With oFooter.Range
            For Each tbl In .Tables
                tbl.Select
                If Selection.Bookmarks.Count <> 1 Then
                    tbl.Delete ' <-- pos1
                ElseIf Selection.Bookmarks(1).Name <> "FooterTable" Then
                    tbl.Delete
                Else
                    foundFooterTable = True ' <-- pos2
                    FormatFooterTable tbl 
                End If
            Next
        End With
        oFooter.Range.Select
        Selection.Collapse wdCollapseStart
        If Not foundFooterTable Then
            Set tbl = ActiveDocument.Tables.Add(Selection.Range, 2, 1)
            tbl.Select
            ActiveDocument.Bookmarks.Add Range:=Selection.Range
, Name:="FooterTable" ' <- pos3
            FormatFooterTable tbl
        End If
    Next oFooter
Next oSection
End Sub

thanks for any ideas about what I might do wrong!

2

2 Answers

2
votes

Try to work without Selection as much as you can. Whenever possible, use a Range object. That will make your code clearer and more reliable.

In order to put a bookmark "around" a table (pos 3):

ActiveDocument.Bookmarks.Add Range:=tbl.Range, Name:="FooterTable"

When this works, you should be able to get the table using:

Dim sFooterTable as String
sFooterTable = "FooterTable"
If ActiveDocument.Bookmarks.Exists(sFooterTable) Then
    Set tbl = ActiveDocument.Bookmarks(sFooterTable).Range.Tables(1)
0
votes

found my mistake: I was applying the same bookmark name on all tables that were found .. this way deleting the previous bookmarks as they need a unique name.

adding a unique identifier in the end (I used an integer now) made the code work.