Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Do Loop locking up looking for "\EndOfDoc" (MSWord)

Status
Not open for further replies.

Bullfrog1870

Technical User
Dec 26, 2005
15
US
I'm trying to loop through a Word document and find all occurrences of a particular word. However, once it finds all of them, the Do-Until loop appears to lock up or get stuck since it really hasn't hit the end of document. If I change the .Wrap property to wdFindContinue it just loops indefinitely. Either way, I have to kill (Ctl-Alt-Del) Word.

How do I exit my loop once I've found the last occurrence in the document?

Note: I've not put in my actions once I find "NewYork". I haven't gotten that far.

Thank you!


Sub Macro1()
Do Until ActiveDocument.Bookmarks("\Doc") = ActiveDocument.Bookmarks("\EndOfDoc")
Selection.Find.ClearFormatting
With Selection.Find
.Text = "NewYork"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.CorrectHangulEndings = True
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchFuzzy = False
End With
Selection.Find.Execute
Loop
End Sub
 
Code:
Dim r As Range
Set r = ActiveDocument.Range
With r.Find
  Do While .Execute(Findtext:="New York", Forward:=True) = _
          True
' here is where you can change what you do
' when you find each New York
    Do
      .Replacement.Text = ""
      .Execute Format:=False, Replace:=wdReplaceAll, _
            MatchCase:=True
    Loop Until .Found = False
 Loop
End With
Set r = Nothing
No need to use Selection. Using Selection is to be avoided if possible.

When the Do While .Execute of the Find returns a False (there are no more "New York"), it stops.

Gerry
My paintings and sculpture
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top