The Do Loop
The
Do loop has several variations. To describe these
variations, we use the notation:
{While | Until}to represent either the word While or the word
Until, but not both. With this in mind, here are
the possible syntaxes for the Do loop:
Do {While | Until} condition
' code block here
Loopor:
Do
' code block here
Loop {While | Until} conditionActually, there is a fifth possibility, because we can dispense with
condition completely and write:
Do ' code block here Loop
The Do loop is used quite often in DAO programming to iterate through a recordset. Here is a typical example that prints all values of a particular field in a recordset:
Sub DoExample()
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("Objects")
rs.MoveFirst
Do While Not rs.EOF
Debug.Print rs!Name
rs.MoveNext
Loop
rs.Close
End SubWe will discuss the EOF property as well as the MoveFirst and MoveNext methods when we discuss Recordset objects later in the book.
Just as the For loop has an
Exit
For statement for
terminating the loop, a Do loop has an
Exit
Do statement for
exiting the Do loop.
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