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 biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How Use a Loop to Find Text in Word Doc 1

Status
Not open for further replies.

YerMom

Programmer
Oct 3, 2006
127
US

I have a word document in which I need to find text and format the paragraph that the text appears in. I was clueless about the find function, so I recorded a macro to try to learn. I'm still a bit in the dark concerning how to find text within a loop, so I had to pick an arbitrarily large number (1000), which I know exceeds the number of occurances of the text. This is a fragile and inelegant solution. The code I use in my macro follows. Can anyone show me how to modify the code to exit the loop when the last text is found?

Also, I'd like to determine the number of times I found the text (as shown by my feeble use of "counter" in the code below). If you could also let me know how to use counter to that end, I would be very thankful.

Thanks...

Code:
With Selection.Find
        .Text = "Key Fields"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    For i = 1 To 1000
        Selection.Find.Execute
        counter = counter + 1
        With Selection.ParagraphFormat
            .KeepTogether = True
        End With
    Next i
 



Hi,

Give this a try...
Code:
    Dim par As Paragraph, bFound As Boolean
    For Each par In ThisDocument.Paragraphs
        bFound = par.Range.Find.Execute(FindText:="Key Fields")
        If bFound Then
            par.Format.KeepTogether = True
        End If
    Next

Skip,

[glasses] When a group touring the Crest Toothpaste factory got caught in a large cooler, headlines read...
Tooth Company Freeze a Crowd! and
Many are Cold, but Few are Frozen![tongue]
 
Thanks, Skip.

That solution works.
 
Very nice Skip.

YerMom, if you want the count, just add a counter.
Code:
Dim par As Paragraph
Dim bFound As Boolean
Dim j As Long
  For Each par In ThisDocument.Paragraphs
     bFound = par.Range.Find _
        .Execute(FindText:="Key Fields")
     If bFound Then
         par.Format.KeepTogether = True
         j = j + 1
     End If
  Next
Msgbox j & "paragraphs have been formatted."
Or whatever text you want to use.

The key point here though is Skip's code does not use Selection, a very inefficient way to search for things.

faq219-2884

Gerry
My paintings and sculpture
 
fumei,

Thanks for this extra help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top