Reputation: 69
I'd like to find “Proc. Natl. Acad. Sci” in the article, replacing him with “Proc. Natl. Acad. Sci. USA” and highlighting it as green.
I wrote the following code. It only marked “Proc. Natl. Acad. Sci.“ As green and did not mark USA as green. how can I mark whole “Proc. Natl. Acad. Sci. USA” as green?
Sub add_usa()
selection.find.clearforamtting
With selection.Find
.Text = "Proc. Natl. Acad. Sci. "
.Wrap = wdFindContinue
.Forward = True
.MatchCase = False
.MatchWildcards = False
Do
.Execute
If .Found And selection.Range.Next(wdCharacter, 1) <> "U" Then
selection.Range.InsertAfter "USA "
selection.Range.HighlightColorIndex = wdBrightGreen
End If
If Not .Found Then
Exit Do
End If
Loop
End With
End Sub
Upvotes: 0
Views: 25
Reputation: 14373
You can just use Find and Replace:-
Sub Add_USA()
Const ExistingText As String = "Proc. Natl. Acad. Sci."
Const NewText As String = "Proc. Natl. Acad. Sci. USA"
Options.DefaultHighlightColorIndex = wdBrightGreen
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ExistingText
.Replacement.Text = NewText
.Replacement.Highlight = True
.Forward = True
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
End Sub
Upvotes: 1
Reputation: 4956
Put the lines about modifying the range inside a With block:
With Selection.Range
.InsertAfter "USA "
.HighlightColorIndex = wdBrightGreen
End With
(Tested in Word 2010)
Upvotes: 1