Search-Replace till exhaustion in selection/range

H

HONYAKUKA

Word 2000

I'm having trouble writing a macro to search and replace repeatedly till the
target text is completely gone from a predefined range.

The following code works fine for an entire document:

**************
Private Sub FindReplaceTextRepeat(xFind, xReplace)

With Selection
.HomeKey unit:=wdStory
With .Find
Do
.ClearFormatting
.Replacement.ClearFormatting
.Text = xFind
.Replacement.Text = xReplace
.Forward = True
.Wrap = wdFindContinue
.Execute 'Necessary for the .Found property to work.
.Execute Replace:=wdReplaceAll
If .Found = False Then
Exit Do
Else
If Selection.Range.End = ActiveDocument.Range.End Then 'Needed
to prevent endless looping at the final paragraph mark of a document.
GoTo BYE
Else
Selection.HomeKey unit:=wdStory
End If
End If
Loop While .Found = True
End With
End With
ActiveDocument.UndoClear

BYE:
End Sub
***********

But if I select a range of text and define the beginning and ending of that
selection as Ranges (which process an earlier post-er helped me figure out),
and then run the code basically as above (changing .Wrap to .wdFindStop), the
..Execute step, which is needed to make the .Found property work, ruins the
end-point of the defined Range.

In short, in place of the .Found property, what can I use to at the Loop While
step to show that there was or was not a replacement, such that the loop either
continues or stops. Or should I try a whole new approach?

By the way, in a related post someone suggested using wildcards, but I'd rather
not do that, as certain strings (such as ^p) do not work when using wildcards.

Thanks very much.

Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top