如何搜索字符串并突出显示相邻的单词?

How to search for a string and highlight adjacent words?

我有一个很大的 MS Word 文档。为了日后查找信息,我创建了一个索引来识别重要主题。在 MS Word 中使用索引的一个缺点是它们只显示它们引用的信息的页码(而不是索引的单词或句子)。我想突出显示与索引相关的页面部分(以便更容易找到)。

创建索引时,MS Word 会添加索引条目,例如{XE "Index Phrase"} 在被索引的单词或短语之后。此索引条目仅在打开格式标记的情况下查看文档时可见。我找到了下面的代码并对其进行了一些调整以通过搜索“^d”并更改字体颜色来找到索引。

对于不想查看带有格式标记的文档的用户,我想突出显示与索引条目相邻的单词或最好是句子。

我尝试使用 Moveleft 方法调整代码。

Sub ChangeWordColors()
    Dim vWords As Variant
    Dim sWord As Variant

    vWords = Array("^d")

    For Each sWord In vWords
        
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        Selection.Find.Replacement.Font.Color = wdColorRed
                
        With Selection.Find
            .Text = sWord
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Format = True
            .MatchCase = False
            .MatchWholeWord = True
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        
        Selection.Find.Execute Replace:=wdReplaceAll
        
    Next sWord
End Sub

例如:

Sub Demo()
Application.ScreenUpdating = False
Dim Fld As Field, Rng As Range
For Each Fld In ActiveDocument.Fields
  If Fld.Type = wdFieldIndexEntry Then
    Set Rng = Fld.Code
    With Rng
      .Start = .Start - 1
      .Collapse wdCollapseStart
      .MoveStart Unit:=wdSentence, Count:=-1
      .Font.Color = wdColorRed
    End With
  End If
Next
Application.ScreenUpdating = True
End Sub

不过请注意,VBA 不知道语法句子是什么。