如何在 Microsoft Word 中匹配列表中的多个单词

如何在 Microsoft Word 中匹配列表中的多个单词

假设我有一份文件The quick brown fox jumps over the lazy dog

我想查找(最好是替换)列表中某些单词的所有实例,例如the,,foxdog最终结果应如下所示:

快棕狐狸跳过懒惰的

我怎样才能通过一次搜索做到这一点,而不是分别搜索每个单词?

通常我会做类似([Tt]he|fox|dog)正则表达式的事情,但 Word 似乎不支持|管道运算符。

我想要 Microsoft Word 原生的解决方案,不需要插件或外部程序。

答案1

您需要一个宏来搜索多个单词 - 这种功能不属于 Native Word 的一部分。

下面的宏可以为您执行此操作并搜索您的文档。

请参见:

宏来查找多个单词

Sub HiLightList()
Application.ScreenUpdating = False
Dim StrFnd As String, Rng As Range, i As Long
StrFnd = "dog,cat,pig,horse,man"
For i = 0 To UBound(Split(StrFnd, ","))
  Set Rng = ActiveDocument.Range
  With Rng.Find
    .ClearFormatting
    .Text = Split(StrFnd, ",")(i)
    .Replacement.ClearFormatting
    .Replacement.Highlight = True
    .Replacement.Text = "^&"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = True
    .Execute Replace:=wdReplaceAll
  End With
Next
Set Rng = Nothing
Application.ScreenUpdating = True
End Sub

答案2

为此,您将需要使用 VBA 宏。

在文章中发现了以下宏 宏技巧:如何在 Word 文档中突出显示多个搜索字符串。它搜索并突出显示字符串“very”、“just”、“of course”。本文进一步解释了宏中的每个命令。

Sub HighlightWords()
Dim Word As Range
Dim WordCollection(2) As String
Dim Words As Variant
'Define list.
'If you add or delete, change value above in Dim statement.
WordCollection(0) = "very"
WordCollection(1) = "just"
WordCollection(2) = "of course"
'Set highlight color.
Options.DefaultHighlightColorIndex = wdYellow
'Clear existing formatting and settings in Find feature.
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
'Set highlight to replace setting.
Selection.Find.Replacement.Highlight = True
'Cycle through document and find words in collection.
'Highlight words when found.
For Each Word In ActiveDocument.Words
For Each Words In WordCollection
With Selection.Find
.Text = Words
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Next
Next
End Sub

在 Word 帮助中了解宏,也可以阅读文章 宏安装指南。请注意,要使用宏,文档必须是 类型.docm,而不是 .docx

相关内容