General approach to using For Each....

J

Jeff

I need some general advice on using the "For Each x in y" statement

Here is a typical problem where the collection changes, causing the
statement to fail...

Dim aPara As Paragraph
For Each aPara In ActiveDocument.Paragraphs
If some_condition = True Then
aPara.Range.Delete
End If
Next

The above code actually changes the paragraphs collection of the document
and the "Each" part of the for..next loop gets messed up.

This applies not only to the paragraphs collection - the last time I
attempted it, I was removing certain types of hyperlink from a document and
only every second or third hyperlink got processed!

I'm wondering is there a recommended way of using is statement when the code
changes the document model within the loop? The only way I can see of
making it work is to use this....

For p = ActiveDocument.Paragraphs.Count to 1 step -1
If some_condition = True Then
ActiveDocument.Paragraphs(p).Range.Delete
End If
Next
 
J

Jonathan West

Jeff said:
I need some general advice on using the "For Each x in y" statement

Here is a typical problem where the collection changes, causing the
statement to fail...

Dim aPara As Paragraph
For Each aPara In ActiveDocument.Paragraphs
If some_condition = True Then
aPara.Range.Delete
End If
Next

The above code actually changes the paragraphs collection of the document
and the "Each" part of the for..next loop gets messed up.

This applies not only to the paragraphs collection - the last time I
attempted it, I was removing certain types of hyperlink from a document
and
only every second or third hyperlink got processed!

I'm wondering is there a recommended way of using is statement when the
code
changes the document model within the loop? The only way I can see of
making it work is to use this....

For p = ActiveDocument.Paragraphs.Count to 1 step -1
If some_condition = True Then
ActiveDocument.Paragraphs(p).Range.Delete
End If
Next

You have found the only reliable way. *Some* collections work right, others
don't in the way you have discovered. I always use the counting backwards
method for all of Word's built-in collections if items are being added or
deleted.
 

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