Loop stuck

J

JayCharms

The following loop (used to tighten up pagraphs, since I need an
accurate first character later in the process) gets stuck as soon as
the style condition ("if parchk.style=..."is met.

Dim par as paragraph
Dim parchk as range
Dim newtext as string
Dim oldstyle as style
For Each par In ActiveDocument.Paragraphs
Set parchk = par.Range
If parchk.Style = "BNormal" Or parchk.Style = "Summary" Or
parchk.Style = "bucknormal" Then
Set oldstyle = parchk.Style
newtext = Trim(parchk.Text)
par.Range.Text = newtext
par.Range.Style = oldstyle
End If
Next

If I replace the "For each..." with "For x=1 to
activedocument.paragraphs.count", setting
parchk=ActiveDocument.paragraphs(x), the loop processes all the
paragraphs but the style ends up incorrect. Taking out
par.range.style=oldstyle also doesn't work. Any ideas would be
appreciated.
 
B

Bear

JayCharms:

This is one of the things about VBA and the Word document object model that
baffles me from time to time. Some operations on a collection either cause
the collection to be rebuilt or the object in question to be reindexed or
something.

At any rate, I've grown accustomed to just accepting that I have to use "For
x = 1 to activedocument.paragraphs.count" sorts of loops sometimes.

Bear
 
D

David Sisson

Try running the loop backwards.

For x = activedocument.paragraphs.count to 1 step -1

When the object is set in the collection (ActiveDocument.Paragraphs ),
and when you delete paragraphs, the collection isn't updated in the
loop. So your document is getting shorter but your loop doesn't know
that, hence the error.
 

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