Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
DiscussionsAccessExcelInfoPathOutlookPowerPointPublisherWord
DirectoryUser Groups
Related Topics
Outlook ExpressInternet ExplorerWindowsMS Server ProductsMore Topics ...

MS Office Forum / Word / Programming / January 2005

Tip: Looking for answers? Try searching our database.

General approach to using For Each....

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Jeff - 03 Jan 2005 15:03 GMT
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

Rate this thread:






 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.