Microsoft Office Tutorials and References
In Depth Information
8.3 The For Each Loop
If Not IsEmpty(oCell) Then
bNone = False
Exit For
End If
If bNone Then MsgBox "No nonempty cells in row 1", vbInformation
End Sub
We can also control the step size and direction for the counter in a For loop using the Step
keyword. For instance, in the following code, the counter i is incremented by 2 each time the
block of code is executed:
For i = 1 to 10 Step 2
' code block goes here
Next i
The following loop counts down from 10 to 1 in increments of -1. This can be useful when we
want to examine a collection (such as the cells in a row or column) from the bottom up:
For i = 10 to 1 Step -1
' code block goes here
Next i
8.3 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 ObjectVar In CollectionName
' block of code goes here . . .
Next ObjectVar
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.
The FindFirstNonEmpty procedure shown in Example 8-1 illustrates the For Each loop.
Thus, when iterating through a collection of objects, we have two choices:
For Each object in Collection
' code block here
Next object
For i = 1 to Collection.Count
' code block here
Next i
Search JabSto ::

Custom Search