2012-02-22 56 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