How to know if Find/ReplaceAll found anything?

E

Ed

I'm looping through a number of documents using
With rng.Find
.Text = strFind
.Replacement.Text = strRepl
.Format = False
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
How do I tell if this actually did find and replace something? If it did,
I'd like to Debug.Print my document name so I can go back and make sure it
was a good replacement.

Ed
 
H

Helmut Weber

Hi Ed,

like this:

Sub test712348()
Dim rng As Range
Set rng = ActiveDocument.Range
ResetSearch
With rng.Find
.Text = "a"
.Replacement.Text = "b"
If .Execute(Replace:=wdReplaceAll) Then
MsgBox "found and replaced"
Else
MsgBox "nothing found, nothing replaced"
End If
End With
ResetSearch
End Sub
' ---
Public Sub ResetSearch()
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
' plus some more if needed
.Execute
End With
End Sub

Greetings from Bavaria, Germany

Helmut Weber, MVP
"red.sys" & chr(64) & "t-online.de"
Word XP, Win 98
http://word.mvps.org/
 
E

Ed

Okay - I think I follow this. ResetSearch is only to make sure nothing is
left over from a previous search?
And did I modify my code correctly?
' Open doc and replace
Set doc = Documents.Open(fName & dName)
Set rng = doc.Range
ResetSearch
With rng.Find
.Text = strFind
.Replacement.Text = strRepl
.Format = False
.Wrap = wdFindContinue

If .Execute (Replace:=wdReplaceAll) Then
Debug.Print dName
End If

End With
doc.Close SaveChanges:=wdSaveChanges
ResetSearch
 
H

Helmut Weber

Hi Ed,
ResetSearch is only to make sure nothing is
left over from a previous search?

Yes.

And to make sure, options are cleared
for the next search by an end user.

And, if using ResetSearch,
..format and .wrap are redundant, too.

Greetings from Bavaria, Germany

Helmut Weber, MVP
"red.sys" & chr(64) & "t-online.de"
Word XP, Win 98
http://word.mvps.org/
 

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