Word VBA - 通过查找文本返回书签

时间:2018-01-12 14:16:01

标签: vba ms-word word-vba

我正在尝试使用Microsoft Word文档编写一些VBA,该文档将在其自身内部搜索文本字符串,一旦找到它,将返回前面的书签名称。

我目前有以下代码;

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

我似乎无法获取代码来返回前一个书签的唯一标识符,因为我搜索的文本将在2个书签之间找到。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

实际上,选择书签的唯一方法是从Range中查询它们。在您的情况下,您需要从Found范围向后的Range。最简单的方法是将Range设置回Document的开头,然后选择最后一个书签。以下代码示例基于您的原始示例说明了这一点。

请注意,我已将ThisDocument更改为ActiveDocument。 ThisDocument是VBA代码所在的文档对象。我假设您希望代码在当前正在处理的任何文档上运行?在这种情况下,ActiveDocument是正确的。

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