End while vba
Better to use Do While/Loop and then Exit Do. However, for interest, the following example exits the While/Wend in VBA. Dim lngCounter As Long. While lngCounter.VBA While Loop – A Complete Guide
“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).
Contents
A Quick Guide to VBA While Loops
| Loop format | Description | Example |
|---|---|---|
| Do While ... Loop | Runs 0 or more time while condition is true | DoWhile result = "Correct" Loop |
| Do ... Loop While | Runs 1 or more times while condition is true | Do LoopWhile result = "Correct" |
| Do Until ... Loop | Runs 0 or more times until condition is true | DoUntil result <> "Correct" Loop |
| Do ... Until Loop | Runs 1 or more times until condition is true | Do LoopUntil result <> "Correct" |
| While ... Wend | Runs 0 or more times while condition is true. Note: this loop is considered obsolete. | While result = "Correct" Wend |
| Exit the Do Loop | Exit Do | DoWhile i < 10 i = GetTotal If i < 0 Then ExitDo EndIf Loop |
Introduction
If you have never use loops before then you may want to read What are Loops and Why Do You Need Them from my post on the For Loop.
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.
The Do Loop is different. The Do Loop runs
- While a conditon is true
- Until a condition is true
Or
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?
Conditions
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").Value = "John" | Cell A1 contains text "John" |
| Range("A1").Value <> "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.
For example
The following table demonstrates how equals is used in conditions and assignments
| Using Equals | Statement Type | Meaning |
|---|---|---|
| LoopUntil x = 5 | Condition | Is x equal to 5 |
| DoWhile 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
The condition is preceded by While or Until which gives us these four possibilities
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
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’
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 AsString 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 onceDo sCommand = InputBox("Please enter item for Loop 2") LoopWhile sCommand <> "n"EndSub
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.
For example
- Leave the clothes on the line Until it rains
- Leave the clothes on the line While it does not rain
another example
- 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’.
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
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
To write this code using Do While would be more confusing as the condition is Not Is Nothing
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
DoWhile i < 1000 If Cells(i,1) = "Found"ThenExitDoEndIf i = i + 1 Loop
In this case we exit the Do Loop if a cell contains the text “Found”.
While Wend
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 <Condition>
Wend
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
Infinite Loop
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
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.
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.
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 🙂
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
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
Summary
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.
What’s Next?
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.)