在word文档中查找单词使用

时间:2016-08-08 09:04:07

标签: vba ms-word word-vba

我有一个word文档包含一些百分比数字。例如,本月回报率为1.25%"。我想用黄色背景颜色突出显示百分比数字。

1 个答案:

答案 0 :(得分:1)

以下代码查找 1或2位的模式,后跟 dot ,后跟 1或2位数然后是并突出显示它(例如1.2%,1.23%,12.3%或12.34%):

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
With Selection.Find
    .Text = "[0-9]{1,2}%"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll

这个模式 1或2位数,然后是,并突出显示它(例如1%,12%):

Public MyPattern As String

Sub MainSub()

    MyPattern = "[0-9]{1,2}.[0-9]{1,2}%"
    HighlightPattern

    MyPattern = "[0-9]{1,2}%"
    HighlightPattern

    MyPattern = "-[0-9]{1,2}.[0-9]{1,2}%"
    HighlightPattern

    MyPattern = "-[0-9]{1,2}%"
    HighlightPattern

End Sub

Sub HighlightPattern()

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
With Selection.Find
    .Text = MyPattern
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll

End Sub

希望这能满足您的需求

修改 如果你还想强调数字前面的负号,我建议你这样做,以避免一次又一次地复制代码:

{{1}}