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
Jonathan West - 04 Jan 2005 01:08 GMT
>I need some general advice on using the "For Each x in y" statement
>
[quoted text clipped - 26 lines]
> 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.

Signature
Regards
Jonathan West - Word MVP
www.intelligentdocuments.co.uk
Please reply to the newsgroup
Jeff - 04 Jan 2005 15:34 GMT
No takers? I guess it can't be done that way!
> I need some general advice on using the "For Each x in y" statement
>
[quoted text clipped - 24 lines]
> End If
> Next