“Now… We are going in a loop” ― Ramakrishna, Springs of Indian Wisdom
This post provides a complete guide to the VBA Do While and VBA While Loops. (If you’re looking for information about the VBA For and For Each loops go here)
The VBA While loop exists to make it compatible with older code. However, Microsoft recommends that you use the Do Loop as it is more “structured and flexible”. Both of these loops are covered in this post.
For a quick guide to these loops check out the Quick Guide Table below.
If you are looking for something in particular, you can check out the Table of Contents below(if it’s not visible click on the post header).
- 1 A Quick Guide to VBA While Loops
- 2 Introduction
- 3 For Loops Versus Do While Loops
- 4 Conditions
- 5 The Do Loop Format
- 6 Exit Do Loop
- 7 While Wend
- 8 Infinite Loop
- 9 Using Worksheet Functions Instead of Loops
- 10 Summary
- 11 What’s Next?
- 12 Get the Free eBook
A Quick Guide to VBA While Loops
|Do While ... Loop||Runs 0 or more time while condition is true||Do While result = "Correct"
|Do ... Loop While||Runs 1 or more times while condition is true||Do
Loop While result = "Correct"
|Do Until ... Loop||Runs 0 or more times until condition is true||Do Until result <> "Correct"
|Do ... Until Loop||Runs 1 or more times until condition is true||Do
Loop Until result <> "Correct"
|While ... Wend||Runs 0 or more times while condition is true.|
Note: this loop is considered obsolete.
|While result = "Correct"
|Exit the Do Loop||Exit Do||Do While i < 10
i = GetTotal
If i < 0 Then
I am going to be mainly concentrating on the Do Loop in this post. As I mentioned above, we have seen the While Wend loop is considered obsolete. For completeness, I have included a section on While Wend later in the post.
So first of all why do we need Do While loops when we already have For loops?
For Loops Versus Do While Loops
When we use a For Loop, we know in advance how many times we want to run it. For example, we may want to run the loop once for each item in a Collection, Array or Dictionary.
In the following code example, we know at the start of each loop, how many times it will run.
' runs 5 times For i = 1 To 5 ' runs once for each item in the collection For i = 1 To coll.Count ' runs once for each item in the arr For i = LBound(arr) To coll.lbound(arr) ' runs once for each value between 1 and the value in lastRow For i = 1 To lastRow ' runs once for each item in the collection For Each s In coll
The Do Loop is different. The Do Loop runs
- While a conditon is true
- Until a condition is true
In other words, the number of times the loops runs is not relevant in most cases.
So what is a condition and how do we use them?
A condition is a statement that evaluates to true or false. They are mostly used with Loops and If statements. When you create a condition you use signs like >,<,<>,>=,=.
The following are examples of conditions
|Condition||This is true when|
|x < 5||x is less than 5|
|x <= 5||x is less than or equal to 5|
|x > 5||x is greater than 5|
|x >= 5||x is greater than or equal to 5|
|x = 5||x is equal to 5|
|x <> 5||x does not equal 5|
|x > 5 And x < 10||x is greater than 5 AND x is less than 10|
|x = 2 Or x >10||x is equal to 2 OR x is greater than 10|
|Range("A1") = "John"||Cell A1 contains text "John"|
|Range("A1") <> "John"||Cell A1 does not contain text "John"|
You may have noticed x=5 as a condition. This should not be confused with x=5 when used as an assignment.
' means: the value 6 will be stored in x x = 6 ' means: is x equal to 6? If x = 6 ' means: is x equal to 6? Do While x = 6
The following table demonstrates how equals is used in conditions and assignments
|Using Equals||Statement Type||Meaning|
|Loop Until x = 5||Condition||Is x equal to 5|
|Do While x = 5||Condition||Is x equal to 5|
|If x = 5 Then||Condition||Is x equal to 5|
|For x = 1 To 5||Assignment||Set the value of x to 1, then to 2 etc.|
|x = 5||Assignment||Set the value of x to 5|
|b = 6 = 5||Assignment and Condition||Assign b to the result of condition 6 = 5|
|x = MyFunc(5,6)||Assignment||Assign x to the value returned from the function|
The Do Loop Format
The Do loop can be used in four ways and this often causes confusion. However, there is only a slight difference in each of these four ways.
Do is always at the start of the first line and Loop is always at the end of the last line
We can add a condition after either line
Do [condition] Loop Do Loop [condition]
The condition is preceded by While or Until which gives us these four possibilities
Do While [condition] Loop Do Until [condition] Loop Do Loop While [condition] Do Loop Until [condition]
Let’s have a look at some examples to make this clearer.
A Do Loop Example
Imagine you want the user to enter a list of items. Each time the user enters an item you print it to the Immediate Window. When the user enters a blank string, you want the application to end.
In this case the For loop would not be suitable as you do not know how many items the user will enter. The user could enter the blank string first or on the hundredth attempt. For this type of scenario, you would use a Do loop.
The following code shows an example of this
Dim sCommand As String Do ' Get user input sCommand = InputBox("Please enter item") ' Print to Immediate Window(Ctrl G to view) Debug.Print sCommand Loop While sCommand <> ""
The code enters the loop and continues until it reaches the “Loop While” line. At this point, it checks whether the condition evaluates to true or false.
- If the condition evaluates to false then the code exits the loop and continues on.
- If the condition evaluates to true then the code returns to the Do line and runs through the loop again.
The difference between having the condition on the Do line and on the Loop line is very simple
When the condition is on the Do line, the loop may not run at all. So it will run zero or more times.
When the condition is on the Loop line, the loop will always run at least once. So it will run one or more times.
In our the last example, the condition is on the Loop line because we always want to get at least one value from the user. In the following example, we use both versions of the loop. The loop will run while the user does not the enter the letter ‘n’
' https://excelmacromastery.com/ Sub GetInput() Dim sCommand As String ' Condition at start Do While sCommand <> "n" sCommand = InputBox("Please enter item for Loop 1") Loop ' Condition at end Do sCommand = InputBox("Please enter item for Loop 2") Loop While sCommand <> "n" End Sub
In the above example, both loops will behave the same.
However, if we set sCommand to ‘n’ before the Do While loop starts, then the code will not enter the loop.
' https://excelmacromastery.com/ Sub GetInput2() Dim sCommand As String sCommand = "n" ' Loop will not run as command is "n" Do Whilel sCommand <> "n" sCommand = InputBox("Please enter item for Loop 1") Loop ' Loop will still run at least once Do sCommand = InputBox("Please enter item for Loop 2") Loop While sCommand <> "n" End Sub
The second loop in the above example(i.e. Loop While) will always run at least once.
While Versus Until
When you use the Do Loop the condition mush be preceded by Until or While.
Until and While are essentially the opposite of each other. They are used in VBA in a similar way to how they are used in the English language.
- Leave the clothes on the line Until it rains
- Leave the clothes on the line While it does not rain
- Stay in bed Until it is light
- Stay in bed While it is dark
yet another example
- repeat Until the count is greater than or equals ten
- repeat While the count is less than ten
As you can see – using Until and While is just the opposite way of writing the same condition.
Examples of While and Until
The following code shows the ‘While’ and ‘Until’ loops side by side. As you can see the only difference is the condition is reversed. Note: The signs <> means ‘does not equal’.
' https://excelmacromastery.com/ Sub GetInput() Dim sCommand As String ' Condition at start Do Until sCommand = "n" sCommand = InputBox("Please enter item for Loop 1") Loop Do While sCommand <> "n" sCommand = InputBox("Please enter item for Loop 1") Loop ' Condition at end Do sCommand = InputBox("Please enter item for Loop 2") Loop Until sCommand = "n" Do sCommand = InputBox("Please enter item for Loop 2") Loop While sCommand <> "n" End Sub
First loop: will only start if sCommand does not equal ‘n’.
Second loop: will only start if sCommand does not equal ‘n’.
Third loop: will run at least once before checking sCommand.
Fourth loop: will run at least once before checking sCommand.
Example: Checking Objects
An example of where Until and While are useful is for checking objects. When an object has not been assigned it has the value Nothing.
So when we declare a workbook variable in the following example it has a value of nothing until we assign it to a valid Workbook
Dim wrk As Workbook
The opposite of Nothing is Not Nothing which can be confusing.
Imagine we have two functions called GetFirstWorkbook and GetNextWorkbook which return some workbook objects. The code will print the name of the workbook until the functions no longer return a valid workbook.
You can see the sample code here
Dim wrk As Workbook Set wrk = GetFirstWorkbook() Do Until wrk Is Nothing Debug.Print wrk.Name Set wrk = GetNextWorkbook() Loop
To write this code using Do While would be more confusing as the condition is Not Is Nothing
Dim wrk As Workbook Set wrk = GetFirstWorkbook() Do While Not wrk Is Nothing Debug.Print wrk.Name Set wrk = GetNextWorkbook() Loop
This makes the code clearer and having clear conditions is always a good thing. To be honest this is a very small difference and choosing between While and Until really comes down to a personal choice.
Exit Do Loop
We can exit any Do loop by using the Exit Do statement.
The following code shows an example of using Exit Do
Do While i < 1000 If Cells(i,1) = "Found" Then Exit Do End If i = i + 1 Loop
In this case we exit the Do Loop if a cell contains the text “Found”.
This loop is in VBA to make it compatible with older code. Microsoft recommends that you use the Do loops as they are more structured.
From MSDN: “The Do…Loop statement provides a more structured and flexible way to perform looping.”
Format of the VBA While Wend Loop
The VBA While loop has the following format
While Wend vs Do
The different between the VBA While and the VBA Do Loop is :
- While can only have a condition at the start of the loop.
- While does not have a Until version.
- There is no statement to exit a While loop like Exit For or Exit Do.
The condition for the VBA While loop is the same as for the VBA Do While loop. The two loops in the code below perform exactly the same way
' https://excelmacromastery.com/ Sub GetInput() Dim sCommand As String Do While sCommand <> "n" sCommand = InputBox("Please enter item for Loop 1") Loop While sCommand <> "n" sCommand = InputBox("Please enter item for Loop 2") Wend End Sub
Even if you have never written code in your life I’m sure you’ve heard the phrase Infinite Loop. This is a loop where the condition will never be met. It normally happens when you forget to update the count.
The following code shows an infinite loop
Dim cnt As Long cnt = 1 ' Do not run - this is an infinite loop Do While cnt <> 5 Loop
In this example cnt is set to 1 but it is never updated. Therefore the condition will never be met – cnt will always be less than 5.
In the following code the cnt is being updated each time so the condition will be met.
Dim cnt As Long cnt = 1 Do While cnt <> 5 cnt = cnt + 1 Loop
As you can see using a For Loop is safer for counting as it automatically updates the count in a loop. The following is the same loop using For.
Dim i As Long For i = 1 To 4 Next i
This is clearly a better way of doing it. The For Loop sets the initial value, condition and count in one line.
Of course it is possible to have an infinite loop using For – It just takes a bit more effort 🙂
Dim i As Long ' DO NOT RUN - Infinite Loop For i = 1 To 4 ' i will never reach 4 i = 1 Next i
Dealing With an Infinite Loop
When you have an infinite loop – VBA will not give an error. You code will keep running and the Visual Basic editor will not respond.
In the old days you could break out of a loop by simply pressing Ctrl and Break. Nowadays different Laptops use different key combinations. It is a good idea to know what this is for your laptop so that if an infinite loop occurs you can stop the code easily.
You can also break out of a loop by killing the process. Press Ctrl+Shift+Esc. Under the Processes tab look for Excel/Microsoft Excel. Right-click on this and select “End Process”. This will close Excel and you may lose some work – so it’s much better to use Ctrl+Break or it’s equivalent.
Using Worksheet Functions Instead of Loops
Sometimes you can use a worksheet function instead of using a loop.
For example, imagine you wanted to add the values in a list of cells. You could do this using a loop but it would be more efficient to use the worksheet function Sum. This is quicker and saves you a lot of code.
It is very easy to use the Worksheet functions. The following is an example of using Sum and Count
' https://excelmacromastery.com/ Sub WorksheetFunctions() Debug.Print WorksheetFunction.Sum(Range("A1:A10")) Debug.Print WorksheetFunction.Count(Range("A1:A10")) End Sub
The following example use a loop to perform the same action. As you can see it is a much longer way of achieving the same goal
' https://excelmacromastery.com/ Sub SumWithLoop() Dim total As Long, count As Long Dim rg As Range For Each rg In Range("A1:A10") ' Total total = total + rg ' Count If rg <> "" Then count = count + 1 End If Next rg Debug.Print total Debug.Print count End Sub
The Do While Loop
- The Do loop can be used in 4 ways.
- It can be used with While at the start or end, Do While .. Loop, Do … Loop While
- It can be used with Until at the start or end, Do Until .. Loop, Do … Loop Until
- While and Until use the opposite condition to each other.
- An Infinite loop occurs if your exit condition will never be met.
- Sometimes using a worksheet function is more efficient than using a loop.
The While Wend Loop
- The While Wend loop is obsolete and you can use the Do Loop instead.
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)
Get the Free eBook
Please feel free to subscribe to my newsletter and get exclusive VBA content that you cannot find here on the blog, as well as free access to my eBook, How to Ace the 21 Most Common Questions in VBA which is full of examples you can use in your own code.