
iLearn Excel VBA: Do-While-Loop
A Different Kind of Loop
A Do-While-Loop is similar to a For-Loop in the sense that they are both iteration statements. The only difference is that the Do-While-Loop has a conditional statement that it uses to determine whether or not the loop shall continue. Take a look:
Sub TheDoWhileLoop()
Dim x As Integer
x = 1
Do While (x <= 10)
Debug.Print x
x = x + 1
Loop
End Sub
After executing the code above you should get the integers 1-10 displayed in your immediate window. Line 4 reads exactly as it shows, keep looping while x is less than or equal to 10. We print x in line 5 and increase it’s value by 1 in line 6. Then the loop statement in line 7 sends it back to line 4. This is exactly what the For-Loop did, but instead you have to manually change the variable that is in the conditional statement, which can lead to . . .
The Loop . . . It’s Never Ending!!!
READ THIS WHOLE SECTION BEFORE TRYING THIS!! Try deleting line 6 and re-running the code. Finished yet? How about now? Notice that because we never increase the x value manually the conditional statement will always be true because x will remain 1. This is called a never ending loop. I have run into many a never ending loops in my day and unless you are a programming prodigy, you will too. There are a couple ways to get out of this never ending loop, here are a few:
Steps to take to kill your code execution:
- Hit the Escape Key a couple times
- Hit the Pause/Break Key a couple times
- Press Ctrl+C a couple times
- If none of the above key combos worked then Ctrl+Alt+Delete and kill Excel
Join me next time as I talk about the under appreciated Select-Case, signing off ~iAtoria.

