1
votes

I'm trying to write some VBA with a Microsoft Word Document that will search for a text string within itself, and once it has found it, will return the preceding bookmark name.

I currently have the below code;

Public Sub FindDocument()

Dim wrdThis As Document
Dim strSearch As String
Dim myRange As Range
Dim lngBookMark As Long
Dim lngHeadingName As Long
Dim varBookmarks As Variant
Dim i As Integer

Set wrdThis = ThisDocument
Set myRange = wrdThis.Content

strSearch = "ID: VTER"

varBookmarks = wrdThis.GetCrossReferenceItems(wdRefTypeBookmark)

myRange.Find.Execute FindText:=strSearch, Forward:=True
If myRange.Find.Found = True Then
    lngBookMark = myRange.BookmarkID
    MsgBox "Search text found in bookmark " & varBookmarks(lngBookMark)
End If

End Sub

I can't seem to get the code to return a unique identifier for the preceding bookmark as the text I am searching for will be found between 2 bookmarks.

Any help would be greatly appreciated.

1

1 Answers

2
votes

The only way, really, to pick up bookmarks is to query them from a Range. In your case, you need the Range from the Found range backwards. Simplest would simply be to set the Range back to the start of the Document, then pick up the last bookmark. The following code sample, based on your original, illustrates this.

Note that I've changed ThisDocument to ActiveDocument. ThisDocument is the document object in which your VBA code resides. I'm assuming you want the code to run on whichever document is currently being worked on? In that case, ActiveDocument is correct.

Sub FindThenPrevBookmark()
    Dim wrdThis As Document
    Dim strSearch As String
    Dim myRange As Range, rngToStart As word.Range
    Dim bkm As word.Bookmark
    'Dim lngBookMark As Long
    'Dim lngHeadingName As Long
    'Dim varBookmarks As Variant
    'Dim i As Integer

    Set wrdThis = ActiveDocument
    Set myRange = wrdThis.content

    strSearch = "Home"

    'Ensure that Execute and Found are performed on the same FIND
    With myRange.Find
        .Execute findText:=strSearch, Forward:=True
        If .found = True Then
            'Always use DUPLICATE to "copy" a Range object!
            Set rngToStart = myRange.Duplicate
            rngToStart.Start = wrdThis.content.Start
            If rngToStart.Bookmarks.Count > 0 Then
                Set bkm = rngToStart.Bookmarks(rngToStart.Bookmarks.Count)
                MsgBox "Search text found in bookmark " & bkm.Name
            End If
        End If
    End With
End Sub