VBA While Loop
VBA While Loop
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).
Do While ... Loop Runs 0 or more time while condition is true Do While result = "Correct"
Loop
Do Until ... Loop Runs 0 or more times until condition is true Do Until result <> "Correct"
Loop
While ... Wend Runs 0 or more times while condition is true. While result = "Correct"
Wend
Note: this loop is considered obsolete.
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?
In the following code example, we know at the start of each loop, how many times it will run.
For i = 1 To 5
For i = 1 To coll.Count
' runs once for each value between 1 and the value in lastRow
For i = 1 To lastRow
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
x=5 x is equal to 5
You may have noticed x=5 as a condition. This should not be confused with x=5 when used as an assignment.
For example
x = 6
If x = 6
The following table demonstrates how equals is used in conditions and assignments
Do is always at the start of the first line and Loop is always at the end of the last line
Do
Loop
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
Do
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.
Do
Debug.Print 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’
Sub GetInput()
Loop
Do
End Sub
Sub GetInput2()
sCommand = "n"
Loop
Do
End Sub
The second loop in the above example(i.e. Loop While) will always run at least once.
For example
another example
As you can see – using Until and While is just the opposite way of writing the same condition.
Sub GetInput()
Loop
Loop
Do
Do
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.
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
Debug.Print wrk.Name
Loop
To write this code using Do While would be more confusing as the condition is Not Is Nothing
Debug.Print wrk.Name
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
Exit Do
End If
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.”
While Wend vs Do
The different between the VBA While and the VBA Do Loop is :
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
Sub GetInput()
Loop
Wend
End Sub
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.
cnt = 1
Loop
In this example cnt is set to 1 but it is never updated. Therefore the condition will never be met – cntwill always be less
than 5.
In the following code the cnt is being updated each time so the condition will be met.
cnt = 1
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
For i = 1 To 4
i = 1
Next i
It is very easy to use the Worksheet functions. The following is an example of using Sum and Count
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
Sub SumWithLoop()
Dim rg As Range
' Total
total = total + rg
' Count
count = count + 1
End If
Next rg
Debug.Print total
Debug.Print count
End Sub
Summary