Excel VBA Programming - Do Loops
Excel VBA Programming - Do Loops
Home Excel
and LearnVBA
Excel VBA Do
Loops
The Do While loop is a lot easier to use than the For loop you
used in the previous lesson, as you don't need to set a start
https://www.homeandlearn.org/excel_vba_do_loops.html 1/7
21/03/2021 Excel VBA Programming Do Loops
Do While [CONDITION]
Loop
Do While x < y
Here, the loop goes round and round until the test condition at
the start evaluates to FALSE. As soon as VBA detects that your
test condition is FALSE it will exit the loop and continue on its
way.
counter = counter + 1
Loop
If you like, you can add your condition at the end, just after the
word Loop:
Do
counter = counter + 1
The di�erence here is that any code you have for you loop will
execute at least once, if the condition is at the end. If the
condition is at the start then the loop code won't get executed if
the condition already evaluate to FALSE (counter might not be
less than 5, in our code above).
https://www.homeandlearn.org/excel_vba_do_loops.html 3/7
21/03/2021 Excel VBA Programming Do Loops
counter = counter + 1
counter + 1
Because counter changes each time round the loop we can use
it in between the round brackets of Cells, for the Rows value.
The Column we've chosen is the D column.
Run your code and your spreadsheet will now look like this:
https://www.homeandlearn.org/excel_vba_do_loops.html 4/7
21/03/2021 Excel VBA Programming Do Loops
And here's the times table programme again, but this time using
a Do While Loop. Give it a try:
Do Until Loop
counter = counter + 1
Loop
https://www.homeandlearn.org/excel_vba_do_loops.html 5/7
21/03/2021 Excel VBA Programming Do Loops
counter = counter + 1
Loop
If you need to bail out early from any loop then you only need
the word Exit followed by the loop name:
If counter = 0 Then
Exit Do
Else
End If
Loop
The above applies to For loops, as well: just put Exit For if you
need to bail out early.
https://www.homeandlearn.org/excel_vba_do_loops.html 6/7
21/03/2021 Excel VBA Programming Do Loops
Lots more free online courses here on our main Home and
Learn site
https://www.homeandlearn.org/excel_vba_do_loops.html 7/7