我正在尝试在 MS Word 文档中查找所有关键词实例并更改它们的样式。关键字存储在一个数组中,我只想更改特定单词的样式。理想情况下,这会在我打字时发生,但这并不重要。
尝试 1 - 基于录制宏和更改搜索词
Sub Woohoo()
Dim mykeywords
mykeywords= Array("word1","word2","word3")
For myword= LBound(mykeywords) To UBound(mykeywords)
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Style = ActiveDocument.Styles("NewStyle")
With Selection.Find
.Text = mykeywords(myword)
.Replacement.Text = mykeywords(myword)
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Next
End Sub
这会改变单词所在的整个段落的样式。
尝试 2 - 基于此问题,如何在 VBA 的范围/选择中替换 Microsoft Word 字符样式?:
Sub FnR2()
Dim rng As Range
Dim mykeywords
mykeywords = Array("word1","word2","word3")
For nKey = LBound(mykeywords) To UBound(mykeywords)
For Each rng In ActiveDocument.Words
If IsInArray(rng, mykeywords(nKey)) Then
rng.Style = ActiveDocument.Styles("NewStyle")
End If
Next
Next
End Sub
这会查找单行中的单词,但由于某种原因会跳过段落中的单词,例如它找到
Some text
word1
more text
但不是
Some text before word1 means that the code above doesn't change the format
Word1 also isn't changed in this instance
尝试 3 - 自动更正;实际上没有尝试过:
作为替代方案,我正在考虑使用自动更正。但是,我有 100 多个关键字,不知道如何自动将其添加到自动更正列表中(我是 VBA 文盲)。使用这种方法我会看到的另一个问题是我相信自动更正是全局的,而我只需要它来处理特定的文档。