2012-02-22 108 views
5

我的目的是创建一个非常基本的宏以查找一系列单词并突出显示它们。不幸的是,我不知道如何一步完成多个单词。例如,下面的代码工作:用于突出显示多个单词的Microsoft Word宏

Sub Macro1() 
' 
' Macro1 Macro 
' 
' 
    Selection.Find.ClearFormatting 
    Selection.Find.Replacement.ClearFormatting 
    Selection.Find.Replacement.Highlight = True 
    With Selection.Find 
     .Text = "MJ:" 
     .Replacement.Text = "" 
     .Forward = True 
     .Wrap = wdFindContinue 
     .Format = True 
     .MatchCase = True 
     .MatchWholeWord = False 
     .MatchWildcards = False 
     .MatchSoundsLike = False 
     .MatchAllWordForms = False 
    End With 
    Selection.Find.Execute Replace:=wdReplaceAll 
End Sub 

不过,如果我加入另一个.Text =线,那么MJ:被忽略。有任何想法吗?

回答

3

如果您只是在寻找一些简单的词,只需在同一个宏中进行多次查找和替换就可以实现您想要的功能。例如,下面会以黄色突出显示“目标1”和“TARGET2”

Sub HighlightTargets() 

' --------CODE TO HIGHLIGHT TARGET 1------------------- 
    Options.DefaultHighlightColorIndex = wdYellow 
    Selection.Find.ClearFormatting 
    Selection.Find.Replacement.ClearFormatting 
    Selection.Find.Replacement.Highlight = True 
    With Selection.Find 
     .Text = "target1" 
     .Replacement.Text = "target1" 
     .Forward = True 
     .Wrap = wdFindContinue 
     .Format = True 
     .MatchCase = False 
     .MatchWholeWord = False 
     .MatchWildcards = False 
     .MatchSoundsLike = False 
     .MatchAllWordForms = False 
    End With 
    Selection.Find.Execute Replace:=wdReplaceAll 

' --------CODE TO HIGHLIGHT TARGET 1------------------- 
    Options.DefaultHighlightColorIndex = wdYellow 
    Selection.Find.ClearFormatting 
    Selection.Find.Replacement.ClearFormatting 
    Selection.Find.Replacement.Highlight = True 
    With Selection.Find 
     .Text = "target2" 
     .Replacement.Text = "target2" 
     .Forward = True 
     .Wrap = wdFindContinue 
     .Format = True 
     .MatchCase = False 
     .MatchWholeWord = False 
     .MatchWildcards = False 
     .MatchSoundsLike = False 
     .MatchAllWordForms = False 
    End With 
    Selection.Find.Execute Replace:=wdReplaceAll 
End Sub 

或者下面的代码将让你添加的所有条款在同一行这可能是比较容易的工作,突出的所有地方。

Sub HighlightTargets2() 

Dim range As range 
Dim i As Long 
Dim TargetList 

TargetList = Array("target1", "target2", "target3") ' put list of terms to find here 

For i = 0 To UBound(TargetList) 

Set range = ActiveDocument.range 

With range.Find 
.Text = TargetList(i) 
.Format = True 
.MatchCase = True 
.MatchWholeWord = False 
.MatchWildcards = False 
.MatchSoundsLike = False 
.MatchAllWordForms = False 

Do While .Execute(Forward:=True) = True 
range.HighlightColorIndex = wdYellow 

Loop 

End With 
Next 

End Sub 
+0

谢谢!那个循环正是我所期待的。我希望我能说我明白它是如何运作的,但是如果它有效,那么我很高兴! – 2012-05-18 16:34:22