在Microsoft Word的VBA宏中突出显示文本

时间:2013-08-19 03:27:54

标签: vba replace ms-word highlight word-vba

我正在尝试创建一个宏来搜索文档并突出显示空格的每一个出现,单词“for”,然后使用此站点中的修改代码这样的“for”另一个空格,我得到了这个:

Sub findfunction()
If (findHL(ActiveDocument.Content, "[ for ]")) = True Then MsgBox "Highlight Comma's and Coordinating Conjunctions Done", vbInformation + vbOKOnly, "Highlight Result"
End Sub

Function findHL(r As Range, s As String) As Boolean
Options.DefaultHighlightColorIndex = wdYellow
r.Find.Replacement.Highlight = True
r.Find.Execute MatchWholeWord:=True, FindText:=s, MatchWildcards:=True, Wrap:=wdFindContinue, Format:=True, replacewith:="", Replace:=wdReplaceAll
findHL = True
End Function

问题是它突出了字母f,o和r的每一个出现。我希望它仅在找到序列“for”时突出显示,而不是单个字符。我是新手,我不知道从哪里去,所以任何帮助都将不胜感激。谢谢:D

1 个答案:

答案 0 :(得分:0)

通配符不是必需的。搜索字符串应为“for”和MatchWildcards:= False。

Sub findfunction()
    If (findHL(ActiveDocument.Content, " for ")) = True Then
        MsgBox "Highlight Comma's and Coordinating Conjunctions Done", vbInformation + vbOKOnly, "Highlight Result"
    End If
End Sub

Function findHL(r As Range, s As String) As Boolean
    Options.DefaultHighlightColorIndex = wdYellow
    r.Find.replacement.Highlight = True
    r.Find.Execute MatchWholeWord:=True, FindText:=s, MatchWildcards:=False, Wrap:=wdFindContinue, Format:=True, replacewith:="", Replace:=wdReplaceAll
    findHL = True
End Function