The Do Loop

The Do loop has several variations. To describe these variations, we use the notation:

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 Loop or:

' code block here Loop {While | Until) condition

Actually, there is a fifth possibility, because we can dispense with condition completely and write:

' code block here Loop

Some of these variations are actually quite subtle. For instance, the following code cycles through the cells in the first row of the active worksheet as long as the cells are nonempty:

Do While IsEmpty(ActiveSheet.Rows(1).Cells(i)) i = i + 1 Loop

ActiveSheet.Rows(1).Cells(i).Select

(This code will cause some problems if the first row has no nonempty cells, but let's not worry about that now.) Consider also the following code, whose purpose is similar:

Loop While Not IsEmpty(ActiveSheet.Rows(1).Cells(i)) ActiveSheet.Rows(1).Cells(i).Select

The difference between these two versions is that, in the first case, the IsEmpty condition is checked immediately, before any code within the Do loop is executed. Thus, if the first cell is empty, the condition will fail, no code will be executed within the Do loop, and so this cell will be selected (as it should be).

On the other hand, in the second case, the condition is checked at the end of each loop, so the loop will execute the first time, even if the first cell is empty.

Just as the For loop has an Exit For statement for terminating the loop, a Do loop as an Exit Do statement for exiting the Do loop.

0 0

Post a comment