Microsoft Office Tutorials and References
In Depth Information
8.4 The Do Loop
It is important to keep in mind that the For Each loop can be much faster than the For loop when
dealing with collections of Excel objects. Thus, except for small collections, it is the preferred
method.
8.4 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
Loop
or:
Do
' code block here
Loop {While | Until} condition
Actually, there is a fifth possibility, because we can dispense with condition completely and
write:
Do
' 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:
i = 1
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:
i = 1
Do
i = i + 1
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).
 
Search JabSto ::




Custom Search