Since you want to do several things with the found text, you should use just the
"find" part and not the "replace"; once having located the right place, do the
work; and then find again, in a loop, until there are no more occurrences.
Since you want the Find to locate the entire "word" starting with "xx_" and
continuing until you reach a space or punctuation, you should use a wildcard
search (
http://www.gmayor.com/replace_using_wildcards.htm) for the pattern
"xx_[A-Za-z0-9]@>"
The general outline of the macro is this:
Sub demo()
Dim myDoc As Document
Dim myRg As Range
Dim myText As String
Set myDoc = ActiveDocument
Set myRg = myDoc.Content
With myRg.Find
.Text = "xx_[A-Za-z0-9]@>"
.MatchWildcards = True
.Format = False
.Forward = True
.Wrap = wdFindStop
While .Execute
' At this point, myRg has been
' redefined to cover the found
' text. You can modify it...
myText = myRg.Text
myText = Replace(myText, "xx_", "yy_")
myText = Replace(myText, "a", "1")
myText = Replace(myText, "b", "2")
' etc.
' and then put it back into the document
myRg.Text = myText
' prepare for next loop
myRg.Collapse wdCollapseEnd
Wend
End With
End Sub
The .Execute method returns the value True when it successfully matches the
pattern, or False if there are no more occurrences in the rest of the document.
So the While...Wend loop executes repeatedly until there are no more words that
start with "xx_".
As the comment says, each time .Execute finds a match, the range is redefined to
cover just the found text. Then you can modify the range's contents. The last
part is to move the range to a point after the modified text so the next
..Execute starts at the end of the last match and continues toward the end of the
document.
Besides the fact that this method works (unlike the attempt to test each "word"
in the document for the prefix), it's also _much_ faster than explicitly looping
through all the words in the document.
--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so all
may benefit.