Microsoft Office Tutorials and References
In Depth Information
Executing the Same Code Repeatedly
Note: If you change the loop so that it counts from 2 to 10 and adds 2 (rather
than 1) to Counter with each pass through the loop, the code looks like the
For counter = 2 to 10 Step 2
Debug.Print counter
Running the preceding loop displays the following in the Immediate window:
All Done.
Looping through an array
You can use the Counter variable for a For...Next loop as the subscript
for elements in an array. You can use the LBound() (lower boundary) and
UBound() (upper boundary) functions to automatically return the lowest and
highest subscripts in the array. You can use those values as the start and
end values in the For... statement. The following code creates an array
of four elements and assigns a value — a color name — to each element in
the array. The For...Next loop that follows the array prints the contents
of each array element by using the Counter value as the subscript for each
pass through the loop.
Sub LoopArrayDemo()
‘Declare a variable and an array.
Dim counter As Integer
Dim Colors(3) As String
‘Fill the array.
Colors(0) = “Black”
Colors(1) = “Red”
Colors(2) = “Green”
Colors(3) = “Blue”
Chapter 3
‘Create a loop that shows array contents.
For counter = LBound(Colors) To UBound(Colors)
Debug.Print Colors(counter)
End Sub
In the For statement, LBound(Colors) and UBound(Colors) automatically
fill in the lowest and highest subscript numbers. On the first pass through
the loop, the Debug.Print statement prints the contents of Colors(0). On
the second pass through the loop, Debug.Print displays the contents of
Colors(1), and so on until all array elements print.
Search JabSto ::

Custom Search