Microsoft Office Tutorials and References
In Depth Information
Executing the Same Code Repeatedly
As an example of the first syntax, the code in the following Do Until loop
executes once for each record in a recordset named rst. (A recordset, as
discussed in Chapter 5 of this minibook, is the VBA equivalent of a table in
Access.)
‘Example assumes recordset named rst already exists.
rst.MoveFirst
Do Until rst.EOF()
Debug.Print rst.Fields(“Product Name”)
rst.MoveNext
Loop
Here’s how the loop works: The rst.MoveFirst statement moves the
cursor to the first record in the table. At that point, EOF() (which stands
for end of file) is False because EOF() means “past the last record in the
table.” Because the cursor is at the first record, EOF() is False.
Within the loop, the rst.MoveNext statement moves the cursor to the next
record in the table. EOF() remains False until rst.MoveNext executes
a sufficient number of times to have visited every record in the table. After
visiting the last record, rst.MoveNext moves the cursor to the end of the
file — past the last record. When the cursor is past the last record, EOF()
becomes True, and the loop doesn’t repeat anymore. Instead, Access resumes
executing your code normally at the first statement after the Loop statement.
Using the alternative syntax, in which you define the condition at the bottom
rather than at the top of the loop, you can construct the same sort of loop as
follows:
‘Example assumes recordset named rst already exists.
rst.MoveFirst
Do
Debug.Print rst.Fields(“Product Name”)
rst.MoveNext
Loop Until rst.EOF()
You’ll notice one subtle difference between setting the loop condition at the
top of the loop and setting it at the bottom of the loop. Access checks the
condition before the loop executes for the first time (and each time
thereafter). When you set the condition at the top of the loop, none of the
statements in the loop may execute. Forgetting about recordsets and tables for
the moment, consider the following more generic example:
Counter = 101
Do While Counter < 100
Counter = Counter +1
Loop
‘Statements below the loop.
Search JabSto ::




Custom Search