PDA

View Full Version : Solved: Find, Replace + Highlight



jadie
06-02-2006, 06:53 AM
I have a userform that gathers as many as 16 different bits of information from the user. My macro then checks to see if the user entered information and, if so, calls a subroutine to find and replace all instances within a large document.

The document is set up so that each FindText string is initially highlighted (this is because sometimes the final document will need that information and sometimes not) which allows the user to easily identify and delete information not required after running the macro.

The code below finds and replaces text as desired however, it only 'unhighlights' the first instance of the replaced code. I can see why it does this but don't know how to code a loop to make it unhighlight all instances.


Sub FindAndReplace(FindText As String, replacetext As String)
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = FindText
.Replacement.Text = replacetext
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.Range.HighlightColorIndex = wdNoHighlight
Selection.Find.Execute Replace:=wdReplaceAll
End Sub

mdmackillop
06-03-2006, 09:50 AM
Hi Jadie,
Welcome to VBAX
Try the following


Sub FindAndReplace(FindText As String, ReplaceText As String)

With ActiveDocument.Content.Find
.Text = FindText
.Replacement.Text = ReplaceText
.Highlight = True
.Replacement.Highlight = False
.Format = True
.Execute Replace:=wdReplaceAll
End With

End Sub

jadie
06-05-2006, 05:12 AM
Worked like a champion. Thanks mdmackillop.