Do loop

do loop

You can use Do...Loop statements to run a block of statements a number of times. The statements are repeated either While a condition is True or Until a condition becomes True.

Note
The difference between While and Until is marginal. In the example below you could also have written Do Until rst.EOF which looks simpler because the Not is removed, but still, While is used most often.

Do While Loop

An example is processing records until the end of the table is reached

.
Dim rst As Recordset
Do While Not rst.EOF
    
    rst.MoveNext
Loop

Or maybe you want to process all files in a folder.

Note
You may check the condition before or after you enter the loop. The common place is before, as this well reflects the informatics concept of Precondition which means you test conditions before actually doing your planned program steps. In the before example, only do rst.MoveNext if you have not yet reached the rst.EOF ("end of file").

Exit the loop halfway

It is also possible to exit the loop in the middle of the statements block. In the below example the result of the Step1 procedure call determines if Step2 may be executed, or here even the whole loop may continue.

Do While
    booStep1Succeeded = Step1()
    If booStep1Succeeded = False Then Exit Do
    Step2
Loop

Skip item in current iteration

A common pattern is to exclude cetain items that have a cetain condition.

Tip
To stop an endless loop, press ESC or CTRL+BREAK.