在 MS Word 中包含 VBA RegEx 搜索中的所有故事

Include All Stories in VBA RegEx Search in MS Word

我正在寻找能够在 MS Word 中执行正则表达式搜索的解决方案。我一直在使用以下代码来实现这一点(它突出显示匹配的字符串;然后我可以使用 Word 的内置搜索功能搜索突出显示的实例),但它仅限于主文档。出于我的目的,至关重要的是我能够在我的搜索中包括任何其他故事——尤其是任何尾注 and/or 脚注。

有人有解决方案可以在此类搜索中包含尾注和脚注故事吗?

Sub RegexHighlight()

Set RegExp = CreateObject("VBScript.RegExp")
With RegExp
.Global = True
.Pattern = InputBox("Find what:")
For Each Match In RegExp.Execute(ActiveDocument.Range.Text)
    ActiveDocument.Range(Match.FirstIndex, Match.FirstIndex + Match.Length) _
    .HighlightColorIndex = wdYellow
Next
End With

End Sub

这是一个搜索所有故事的例子

Sub RegexHighlight()

Dim Match As Object
Dim Pattern As String
Dim Story As Range

Pattern = InputBox("Find what:")
If Pattern = "" Then Exit Sub

With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = Pattern
    For Each Story In ActiveDocument.storyRanges
        Do While Not Story Is Nothing
            For Each Match In .Execute(Story)
                Story.SetRange Match.FirstIndex, Match.FirstIndex + Match.Length
                Story.HighlightColorIndex = wdYellow
            Next
            Set Story = Story.NextStoryRange
        Loop
    Next
End With
    
End Sub