The For Each Loop
The For Each loop is a variation on the For loop that was designed to iterate through a collection of objects (as well as through elements in an array) and is generally much more efficient than using the traditional For loop. The general syntax is:
For EachObjectVarInCollectionName' block of code goes here . . . NextObjectVar
where ObjectVar is a variable of the same object type as the objects within the collection. The code block will execute once for each object in the collection.
To illustrate, here is how the earlier example that changes Heading 1 style to Heading 2 style would appear using a For Each loop:
Dim para As Paragraph For each para in ActiveDocument.Paragraphs ' Change style from Heading 1 to Heading 2 If para.Style = "Heading 1" Then para.Style = "Heading 2" End If Next para
As you can see, this code is much more concise.
Thus, when iterating through a collection of objects, we have two choices:
For EachobjectinCollection' code block here Nextobject
or:
Fori= 1 toCollection.Count' code block here Next i
However, I must emphasize the point that the For Each loop can be much faster than the For loop when dealing with collections of Word objects. Thus, except for small collections, it is the preferred method. I will provide a rather dramatic example of this when I discuss an example related to the Style object.
The For Each statement can also be used to iterate through collections of non-object items. For instance, the FontNames collection contains ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access