Databases Reference
In-Depth Information
of code is executed, the loop variable counter is incremented by 1. When counter
exceeds the value end , the block of code is no longer executed. Thus, the code block is
executed a total of end - start + 1 times, each time with a different value of counter .
Note that we can omit the word counter in the last line of a For loop (replacing Next
counter with just Next ). This may cause the For loop to execute a bit more quickly, but
it also detracts a bit from readability.
To illustrate, the following code prints the names of the fields in the Objects table:
Sub PrintFields( )
Dim i As Integer
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("Objects")
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name
Next
rs.Close
End Sub
Note that the limits of the For statement are 0 to rs.Fields.Count - 1 because the fields
are indexed starting at 0 (rather than 1). We will discuss this issue in more detail when we
talk about DAO programming.
For loops are often used to initialize an array. For instance, the code:
For i = 0 To 10
iArray(i) = 0
Next i
assigns a value of 0 to each of the 11 variables iArray (0) through iArray (10).
Note that the loop variable counter will usually appear within the block of code, as it
does in this array-initialization example, but this is not a requirement. However, if it does
appear, we need to be very careful not to change its value, since that will certainly mess
up the For loop. (VBA automatically increments the loop variable each time through the
loop, so we should leave it alone.)
13.3 The Exit For Statement
VBA provides the Exit For statement to exit a For loop prematurely. For instance, the
code in Example 13-1 finds the first field whose type is Integer.
 
Search WWH ::




Custom Search