【问题标题】:Word VBA - Returning the bookmark by finding TextWord VBA - 通过查找文本返回书签
【发布时间】:2018-06-22 00:32:04
【问题描述】:

我正在尝试使用 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 个书签之间找到。

任何帮助将不胜感激。

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

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

    请注意,我已将 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
    

    【讨论】:

    • 非常感谢代码,效果很好。关于 ThisDocument、ActiveDocument 的更改,我将宏存储在要搜索的文档中,因此我将始终使用 ThisDocument。如果我指的是另一个文档,我总是希望指定文档名称。我有很多使用“活动”对象的经验,用户点击错误的对象会产生意想不到的结果。
    • @TomW RE ThisDocument 与 ActiveDocument:好的。大多数人没有意识到这意味着什么,所以我习惯于纠正它:-) 很高兴这个建议对你有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多