Help get me out of a Loop

G

Greg

I have a question about refining a Find and Replace Loop.

I am working on a VBA word indexer where I need to 1) find the word 2)
First Cap and bold the word 3) Index the word.

Simple example:

Word to index "Apples"

Sample text: Apples, apples, apples,

Code:
Dim rngstory As Word.Range
Set rngstory = ActiveDocument.Range
With rngstory.Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWildcards = False
.MatchWholeWord = True
.Wrap = wdFindStop
.Text = "Apples"
.Replacement.Text = .Text
.Replacement.Font.Bold = True
Do
.Execute Replace:=wdReplaceOne
rngstory.Collapse Direction:=wdCollapseEnd
If .Found Then
ActiveDocument.Indexes.MarkEntry _
Range:=rngstory, Entry:=.Text
End If
Loop While .Found
End With
End Sub

Without the IF statement the last instance of apples in the sample text
is indexed twice. I figured out why that is and used the IF statement
to resolve it. My question: Is there a more appropriate method for
defining a Do Loop for this application such that the Loop is executed
only IF the item is found? I thought something like:

..Found = True
Do While .Found
....

But that doesn't work. Thanks.
 
H

Helmut Weber

Hi Greg,
i am not familiar with indices,
but "loop while .found" at the end of the loop
repeats search and following actions included in the loop
after the last found.

I use
with range.find
while .execute ' if search or next search is successfull
...
wend
end with

Compare my answers to the postings of Singeredel.

Greetings from Bavaria, Germany

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

Greg Maxey

Helmut,

Yes I like that. After I posted I crawled my way through and found these
alternative methods

'Don't bother with .Replacement method just redefine the found range
While .Execute
rngstory.Text = .Text
rngstory.Font.Bold = True
rngstory.Collapse Direction:=wdCollapseEnd
ActiveDocument.Indexes.MarkEntry Range:=rngstory, Entry:=.Text
Wend

(Which resembles your method)

and

'Find once then enter the loop and perform while found
.Execute Replace:=wdReplaceOne
Do While .Found
rngstory.Collapse Direction:=wdCollapseEnd
ActiveDocument.Indexes.MarkEntry _
Range:=rngstory, Entry:=.Text
.Execute Replace:=wdReplaceOne
Loop

Did you get my e-mail note?
 

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