MS Word VBA - 找一个单词并改变它的风格

时间:2013-08-28 12:09:12

标签: vba ms-word word-vba word-style

我正在尝试查找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 - 基于此问题How can I replace a Microsoft Word character style within a range/selection in VBA?

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文盲)。我在这种方法中会遇到的另一个问题是我认为自动更正是全局的,而我只需要将其用于特定文档。

1 个答案:

答案 0 :(得分:2)

我相信你的宏没有找到单词的原因是由于前导或尾随空格的存在。假设您已经定义了样式“NewStyle”,从

更改SubFnR2中的if语句
If IsInArray(rng, mykeywords(nKey)) Then

If mykeywords(nkey) = LCase(Trim(rng.Text)) Then

应该解决问题。顺便说一句,如果你想保留单词的样式取决于它是大写还是小写,那么删除LCase部分。

编辑:

我已将子修改包含在下面。我已经根据你给出的例子(剪切并粘贴到单词)测试了它,并且它改变了两个实例word1的样式。

Sub FnR3()
Dim rng As Range
Dim mykeywords
mykeywords = Array("word1", "word2", "word3")
Dim nkey As Integer

For nkey = LBound(mykeywords) To UBound(mykeywords)
For Each rng In ActiveDocument.Words

    If mykeywords(nkey) = LCase(Trim(rng.Text)) Then
        rng.Style = ActiveDocument.Styles("NewStyle")
    End If

Next rng
Next nkey

End Sub

好的,您的文档行为已经描述过,我不太清楚为什么。我检查了选择范围,只选择了单词,但整个段落都被格式化了。我修改了代码来修改选择,如下所示。这只是改变了这个词。

Sub FnR4()
Dim rng As Range
Dim mykeywords
mykeywords = Array("word1", "word2", "word3")
Dim nkey As Integer

For nkey = LBound(mykeywords) To UBound(mykeywords)
    For Each rng In ActiveDocument.Words
        Selection.Collapse
        rng.Select
            If mykeywords(nkey) = LCase(Trim(rng.Text)) Then
                Selection.Style = ActiveDocument.Styles("NewStyle")
            End If

    Next rng
Next nkey

End Sub