查找文本和格式

时间:2013-05-14 12:18:10

标签: ms-word word-vba

我在Word 2007中录制了一个找到单词的宏,将光标向上移动两行,插入三个'***',然后突出显示该行。它适用于找到的单词的第一个实例。我正在努力让它在整个文档中重复,并且我想要找到它的所有实例。

这是我录制的宏的输出。我需要为每个“B”实例重复这些操作。

 Sub HighlightNewItems()
'
' HighlightNewItems Macro
'
'
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "B,"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.MoveUp Unit:=wdLine, Count:=2
    Selection.MoveLeft Unit:=wdWord, Count:=1
    Selection.TypeText Text:="***"
    Selection.TypeParagraph
    Selection.EndKey Unit:=wdLine, Extend:=wdExtend
    Options.DefaultHighlightColorIndex = wdRed
    Selection.Range.HighlightColorIndex = wdRed
    Selection.MoveRight Unit:=wdCharacter, Count:=1
End Sub

1 个答案:

答案 0 :(得分:1)

尝试在With.Selection.Find

中添加以下构造
Do While .Execute
  '(logic that you want to apply after finding string)
Loop

在您的情况下,您的代码看起来像

Sub HighlightNewItems()
'
' HighlightNewItems Macro
'
'
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "B,"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False

      Do While .Execute
        Selection.MoveUp Unit:=wdLine, Count:=2
        Selection.MoveLeft Unit:=wdWord, Count:=1
        Selection.TypeText Text:="***"
        Selection.TypeParagraph
        Selection.EndKey Unit:=wdLine, Extend:=wdExtend
        Options.DefaultHighlightColorIndex = wdRed
        Selection.Range.HighlightColorIndex = wdRed
        Selection.MoveRight Unit:=wdCharacter, Count:=1
      Loop 

    End With

End Sub