Check for Existing Bookmarks

I wrote the code below to create a bookmark for each paragraph in my multilevel list. It works great in a one time shot, but if you add to the ml list and have used {ref} fields it gets messed up.

Sub BkMk()
Dim key As String
Dim i As Integer
Dim b As Bookmark
With ActiveDocument.ListParagraphs
    For i = 1 To .Count
        ActiveDocument.Bookmarks.Add Name:="A" & i, Range:=.Item(i).Range
    Next i
End With
End Sub

Example:

  • [text1] <-- Bookmark Name = A1
  • [text2] <-- Bookmark Name = A2
  • [text3] <-- Bookmark Name = A3
  • {Ref A2} <-- Value when you press F9 is text2

then I add to the list between text1 and text2...

  • [text1] <-- Bookmark Name = A1
  • [addition1] <-- Bookmark Name = A2
  • [addition2] <-- Bookmark Name = A3
  • [text2] <-- Bookmark Name = A4
  • [text3] <-- Bookmark Name = A5
  • {Ref A2} <-- Value when you press F9 is addition1

I would want {Ref A2} to remain text2 (its original assignment).

Any ideas?

July 2nd, 2015 10:06am

Simply add an .Exists test to see whether the bookmark already exists before adding the new one. For example:

Sub BkMk()
Dim key As String
Dim i As Long
Dim b As Bookmark
With ActiveDocument.ListParagraphs
    For i = 1 To .Count
        With ActiveDocument.Bookmarks
          If .Exists("A" & i) = False Then .Add Name:="A" & i, Range:=.Item(i).Range
        End With
    Next i
End With
End Sub

Of course, you might need to go further and add an alternate bookmark to the paragraph concerned if the bookmark is already in use. Better still, though, would be to let Word manage the bookmarking of numbered paragraphs and simply insert cross-references to them (via Insert|Cross Reference>Numbered Item), as needed.

Free Windows Admin Tool Kit Click here and download it now
July 2nd, 2015 8:35pm

Good point. I can just use the Word-managed bookmarks. I don't have Numbered Items but everything I need is a Heading. Thank you!
July 3rd, 2015 8:47am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics