Do Until Loop in Excel VBA – Complete Deep Guide
The Do Until Loop is one of the most useful looping structures in Excel VBA.
It is especially useful when you do not know exactly how many times a piece of code needs to execute.
Instead of saying: "Run this code 100 times", you can say: "Keep running this code until this condition becomes True."
1. What You Will Learn
After completing this lesson, you should be able to understand and use Do Until loops professionally in Excel VBA.
- What is a Do Until Loop?
- Why Do Until is used
- Basic syntax
- How the condition works
- Do Until...Loop
- Do...Loop Until
- Condition at the beginning
- Condition at the end
- Loop execution flow
- Using counters
- Using accumulators
- Using Excel cells
- Processing rows
- Stopping at blank cells
- Stopping at a specific word
- Using If inside Do Until
- Using And
- Using Or
- Using Not
- Using Exit Do
- Nested Do Until loops
- User input validation
- Searching Excel data
- Sales processing
- Report automation
- Infinite loops
- Debugging
- Common mistakes
- Best practices
- Practical projects
- Practice questions
- Practical quiz
- Interview questions
2. Table of Contents
- What is Do Until?
- Basic Syntax
- How the Condition Works
- Do Until...Loop
- Do...Loop Until
- Do Until vs Do While
- Counter Example
- Excel Row Processing
- Loop Until Blank
- Loop Until STOP
- If Inside Loop
- Multiple Conditions
- Exit Do
- Nested Do Until
- User Input
- Search Data
- Sales Project
- Invoice Project
- Infinite Loop
- Debugging
- Common Mistakes
- Best Practices
- Practice Exercises
- Quiz
- Interview Questions
- Summary
3. What is Do Until Loop?
A Do Until Loop repeatedly executes a block of code until a specified condition becomes True.
The most important word to remember is:
Continue executing the code until the condition becomes True.
For example:
Do Until i > 10
Debug.Print i
i = i + 1
Loop
The loop keeps running while:
i > 10
is False.
When:
i > 10
becomes True, VBA stops the loop.
4. Real-Life Example of Do Until
Imagine you are filling a water tank.
You tell the worker:
You do not know exactly how many seconds are required.
The stopping condition is:
TankFull = True
This is the basic idea behind Do Until.
5. Basic Syntax
Syntax 1 – Condition at Beginning
Do Until condition
'Code to execute
Loop
Example:
Do Until i > 10
Debug.Print i
i = i + 1
Loop
Syntax 2 – Condition at End
Do
'Code to execute
Loop Until condition
Example:
Do
Debug.Print i
i = i + 1
Loop Until i > 10
6. How the Do Until Condition Works
Suppose:
i = 1
And:
Do Until i > 5
VBA checks:
Is i greater than 5?
At the beginning:
1 > 5
The answer is:
FalseTherefore VBA enters the loop.
After incrementing:
i = 2
VBA checks again.
This continues until:
i = 6
Now:
6 > 5
is True.
Therefore VBA stops.
7. Do Until Flow
8. Do Until...Loop
In this form the condition is checked before executing the loop body.
Do Until condition
statements
Loop
Example
Sub Example_DoUntil()
Dim i As Long
i = 1
Do Until i > 5
Debug.Print i
i = i + 1
Loop
End Sub
Output:
1 2 3 4 5
9. Step-by-Step Execution
| Iteration | i | Condition i > 5 | Action |
|---|---|---|---|
| 1 | 1 | False | Print 1 |
| 2 | 2 | False | Print 2 |
| 3 | 3 | False | Print 3 |
| 4 | 4 | False | Print 4 |
| 5 | 5 | False | Print 5 |
| 6 | 6 | True | Stop |
10. Do Until Can Execute Zero Times
Consider:
Sub TestZero()
Dim i As Long
i = 20
Do Until i > 10
Debug.Print i
i = i + 1
Loop
End Sub
At the beginning:
20 > 10
is already True.
Therefore the loop does not execute.
Do Until...Loop can execute zero times because
the condition is checked before the loop body.
11. Do...Loop Until
The second form checks the condition at the end.
Do
statements
Loop Until condition
Example
Sub TestLoopUntil()
Dim i As Long
i = 1
Do
Debug.Print i
i = i + 1
Loop Until i > 5
End Sub
Output:
1 2 3 4 5
12. Do...Loop Until Executes at Least Once
Because the condition is checked at the end, the code inside the loop executes at least one time.
Sub AtLeastOnce()
Dim i As Long
i = 100
Do
Debug.Print i
Loop Until i > 10
End Sub
Even though:
100 > 10
is already True, the value 100 is printed once.
13. Do Until vs Do While
| Do Until | Do While |
|---|---|
| Continues until condition becomes True. | Continues while condition is True. |
| Focus is on stopping condition. | Focus is on continuing condition. |
Do Until i > 10 Loop |
Do While i <= 10 Loop |
DO WHILE = Keep going WHILE this is True DO UNTIL = Keep going UNTIL this becomes True
14. Do Until with Counter
Sub CounterExample()
Dim i As Long
i = 1
Do Until i > 10
Debug.Print "Value = " & i
i = i + 1
Loop
End Sub
Here:
iis the counter.i = 1initializes the counter.i = i + 1changes the counter.i > 10controls the loop.
15. Do Until with Countdown
Sub Countdown()
Dim i As Long
i = 10
Do Until i < 1
Debug.Print i
i = i - 1
Loop
End Sub
Output:
10 9 8 7 6 5 4 3 2 1
16. Do Until with Total / Accumulator
A variable that stores a running total is called an accumulator.
Sub CalculateSum()
Dim i As Long
Dim total As Long
i = 1
total = 0
Do Until i > 10
total = total + i
i = i + 1
Loop
MsgBox "Total = " & total
End Sub
Result:
55
17. Do Until with Excel Rows
This is where Do Until becomes extremely useful for Excel automation.
Suppose column A contains:
| Row | Column A |
|---|---|
| 1 | Customer |
| 2 | Rahul |
| 3 | Amit |
| 4 | Neha |
| 5 | Priya |
| 6 | Blank |
Code:
Sub ProcessCustomers()
Dim i As Long
i = 2
Do Until Cells(i, 1).Value = ""
Debug.Print Cells(i, 1).Value
i = i + 1
Loop
End Sub
18. Process Rows Until Blank Cell
This is one of the most common practical uses.
Sub ProcessUntilBlank()
Dim i As Long
i = 2
Do Until Cells(i, 1).Value = ""
Cells(i, 2).Value = _
UCase(Cells(i, 1).Value)
i = i + 1
Loop
End Sub
If column A contains customer names, the code converts them to uppercase in column B.
19. Process Until STOP
Sometimes your data contains a special marker such as STOP.
Sub ProcessUntilStop()
Dim i As Long
i = 2
Do Until UCase(Trim(Cells(i, 1).Value)) = "STOP"
Debug.Print Cells(i, 1).Value
i = i + 1
Loop
End Sub
The loop stops when column A contains:
STOP
20. Do Until with If...Then
You can use an If statement inside the loop.
Sub SalesCategory()
Dim i As Long
i = 2
Do Until Cells(i, 1).Value = ""
If Cells(i, 2).Value >= 100000 Then
Cells(i, 3).Value = "VIP"
ElseIf Cells(i, 2).Value >= 50000 Then
Cells(i, 3).Value = "Good"
Else
Cells(i, 3).Value = "Normal"
End If
i = i + 1
Loop
End Sub
21. Practical Example – Sales Classification
Suppose your worksheet contains:
| A | B | C |
|---|---|---|
| Customer | Sales | Category |
| Rahul | 120000 | |
| Amit | 65000 | |
| Neha | 25000 |
VBA:
Sub ClassifySales()
Dim i As Long
i = 2
Do Until Cells(i, 1).Value = ""
If Cells(i, 2).Value >= 100000 Then
Cells(i, 3).Value = "VIP"
ElseIf Cells(i, 2).Value >= 50000 Then
Cells(i, 3).Value = "Good"
Else
Cells(i, 3).Value = "Normal"
End If
i = i + 1
Loop
End Sub
22. Do Until with AND
You can combine conditions using And.
Sub AndExample()
Dim i As Long
i = 2
Do Until i > 100 And Cells(i, 1).Value = ""
Debug.Print Cells(i, 1).Value
i = i + 1
Loop
End Sub
With And, both conditions must be True before
the loop stops.
23. Do Until with OR
Sub OrExample()
Dim i As Long
i = 2
Do Until i > 100 Or _
UCase(Trim(Cells(i, 1).Value)) = "STOP"
Debug.Print Cells(i, 1).Value
i = i + 1
Loop
End Sub
The loop stops if either condition becomes True.
24. Do Until with NOT
The Not operator reverses a Boolean result.
Dim completed As Boolean
completed = False
Do Until Not completed
Debug.Print "Processing..."
completed = True
Loop
When completed becomes True:
Not completed
becomes False.
For beginners, use simple conditions wherever possible. Complicated Boolean conditions can make loops difficult to understand and debug.
25. Exit Do
Exit Do immediately terminates the current Do loop.
Sub ExitDoExample()
Dim i As Long
i = 1
Do Until i > 100
If i = 10 Then
Exit Do
End If
Debug.Print i
i = i + 1
Loop
End Sub
Although the normal condition is:
i > 100
the loop exits when:
i = 10
26. Practical Example – Search Customer
Suppose customer names are in column A.
Sub FindCustomer()
Dim i As Long
Dim customerName As String
customerName = InputBox("Enter customer name")
i = 2
Do Until Cells(i, 1).Value = ""
If UCase(Trim(Cells(i, 1).Value)) = _
UCase(Trim(customerName)) Then
MsgBox "Customer found at row " & i
Exit Do
End If
i = i + 1
Loop
End Sub
27. Search Customer – Found / Not Found
Sub FindCustomerComplete()
Dim i As Long
Dim customerName As String
Dim found As Boolean
customerName = InputBox("Enter customer name")
i = 2
found = False
Do Until Cells(i, 1).Value = ""
If UCase(Trim(Cells(i, 1).Value)) = _
UCase(Trim(customerName)) Then
found = True
MsgBox "Customer found at row " & i
Exit Do
End If
i = i + 1
Loop
If found = False Then
MsgBox "Customer not found."
End If
End Sub
28. Do Until with User Input
Do Until is useful when you want to keep asking the user for valid information.
Sub GetPositiveNumber()
Dim number As Double
number = 0
Do Until number > 0
number = Val(InputBox( _
"Enter a number greater than 0"))
Loop
MsgBox "Valid number = " & number
End Sub
29. User Input Validation Example
Sub PasswordExample()
Dim password As String
password = ""
Do Until password = "1234"
password = InputBox("Enter password")
If password <> "1234" Then
MsgBox "Incorrect password."
End If
Loop
MsgBox "Access Granted."
End Sub
This example is only for demonstrating VBA loops. It is not a secure authentication system.
30. Nested Do Until Loops
A loop inside another loop is called a nested loop.
Sub NestedDoUntil()
Dim i As Long
Dim j As Long
i = 1
Do Until i > 3
j = 1
Do Until j > 3
Debug.Print _
"i = " & i & _
" , j = " & j
j = j + 1
Loop
i = i + 1
Loop
End Sub
The inner loop completes before the outer loop moves to its next iteration.
31. Practical Example – Multiplication Table
Sub MultiplicationTable()
Dim i As Long
Dim number As Long
number = 5
i = 1
Do Until i > 10
Debug.Print number & _
" x " & _
i & _
" = " & _
number * i
i = i + 1
Loop
End Sub
32. Practical Project – Generate Invoice Numbers
Suppose you want to generate 100 invoice numbers.
Sub GenerateInvoices()
Dim i As Long
i = 2
Do Until i > 101
Cells(i, 1).Value = _
"INV-" & _
Format(i - 1, "0000")
i = i + 1
Loop
End Sub
Result:
INV-0001 INV-0002 INV-0003 INV-0004 ... INV-0100
33. Practical Project – Calculate Sales Total
Suppose column A contains sales values.
Sub TotalSales()
Dim i As Long
Dim total As Double
i = 2
total = 0
Do Until Cells(i, 1).Value = ""
total = total + Cells(i, 1).Value
i = i + 1
Loop
MsgBox "Total Sales = " & _
Format(total, "#,##0.00")
End Sub
34. Practical Project – Reach Target Sales
Imagine column A contains daily sales.
We want to keep adding sales until total sales reach ₹1,00,000.
Sub ReachSalesTarget()
Dim i As Long
Dim total As Double
i = 2
total = 0
Do Until total >= 100000
total = total + Cells(i, 1).Value
i = i + 1
Loop
MsgBox "Target reached."
End Sub
This example assumes enough data exists. In professional VBA, add a maximum row limit to avoid reading beyond the available data.
35. Safe Version of Target Loop
Sub SafeReachSalesTarget()
Dim i As Long
Dim total As Double
i = 2
total = 0
Do Until total >= 100000 Or i > 1000
total = total + Cells(i, 1).Value
i = i + 1
Loop
If total >= 100000 Then
MsgBox "Target reached."
Else
MsgBox "Target could not be reached."
End If
End Sub
36. Practical Project – Copy Data Until Blank
Sub CopyDataUntilBlank()
Dim i As Long
i = 2
Do Until Cells(i, 1).Value = ""
Cells(i, 5).Value = _
Cells(i, 1).Value
i = i + 1
Loop
MsgBox "Data copied successfully."
End Sub
37. Practical Project – Process Status
Suppose column A contains Employee IDs and column B contains Status.
Sub ProcessEmployeeStatus()
Dim i As Long
i = 2
Do Until Cells(i, 1).Value = ""
If UCase(Trim(Cells(i, 2).Value)) = _
"PENDING" Then
Cells(i, 3).Value = "Follow Up"
ElseIf UCase(Trim(Cells(i, 2).Value)) = _
"COMPLETED" Then
Cells(i, 3).Value = "Closed"
Else
Cells(i, 3).Value = "Review"
End If
i = i + 1
Loop
End Sub
38. Professional Excel VBA Version
Avoid depending unnecessarily on the currently active sheet.
Sub ProfessionalExample()
Dim ws As Worksheet
Dim i As Long
Set ws = ThisWorkbook.Worksheets("Data")
i = 2
Do Until ws.Cells(i, 1).Value = ""
ws.Cells(i, 3).Value = _
ws.Cells(i, 2).Value * 10
i = i + 1
Loop
End Sub
The code explicitly tells VBA which worksheet should be used. This makes the macro more reliable when another worksheet is active.
39. Why Use Long for Excel Row Counters?
When working with Excel rows, use:
Dim i As Long
rather than:
Dim i As Integer
A worksheet can contain many more rows than an Integer can safely represent.
40. Infinite Do Until Loop
An infinite loop occurs when the condition never becomes True.
Incorrect Example
Sub InfiniteLoop()
Dim i As Long
i = 1
Do Until i > 10
Debug.Print i
Loop
End Sub
What is wrong?
The value of i never changes.
Therefore:
i > 10
will always be False.
Correct Example
Sub CorrectLoop()
Dim i As Long
i = 1
Do Until i > 10
Debug.Print i
i = i + 1
Loop
End Sub
41. Infinite Loop with Excel Data
Be careful with:
Do Until Cells(i, 1).Value = ""
'Code
Loop
If i never changes, the same cell is checked
repeatedly.
Correct:
Do Until Cells(i, 1).Value = ""
'Code
i = i + 1
Loop
42. How to Debug a Do Until Loop
Method 1 – Debug.Print
Debug.Print i
Method 2 – Print Cell Value
Debug.Print Cells(i, 1).Value
Method 3 – Breakpoint
Click the left side of the VBA editor next to a line of code to create a breakpoint.
Method 4 – Immediate Window
Press:
Ctrl + G
to open the Immediate Window.
43. Common Mistakes
Mistake 1 – Forgetting to Change the Counter
Do Until i > 10
Debug.Print i
Loop
This can create an infinite loop.
Mistake 2 – Wrong Condition
Do Until i < 10
i = i + 1
Loop
If i starts at 1, the loop stops only after the
value becomes less than 10.
Mistake 3 – Confusing Until with While
Do While condition
'Continue while condition is True
Loop
Do Until condition
'Continue until condition becomes True
Loop
Mistake 4 – Using ActiveSheet Unnecessarily
Prefer:
ws.Cells(i, 1).Value
over relying on:
Cells(i, 1).Value
when writing professional macros.
44. Best Practices
-
Use
Option Explicit. - Declare your variables.
-
Use
Longfor Excel row counters. - Initialize the counter before entering the loop.
- Make sure the loop condition can eventually become True.
- Avoid unnecessarily complicated conditions.
- Use worksheet variables.
-
Use
Exit Dowhen an early exit is logically required. - Use maximum-row safeguards when processing uncertain data.
- Test your macro on a copy of important data.
45. Professional Coding with Option Explicit
Option Explicit
Sub ProfessionalDoUntil()
Dim ws As Worksheet
Dim i As Long
Set ws = ThisWorkbook.Worksheets("Data")
i = 2
Do Until ws.Cells(i, 1).Value = ""
ws.Cells(i, 2).Value = _
UCase(ws.Cells(i, 1).Value)
i = i + 1
Loop
End Sub
Option Explicit forces you to declare variables
before using them.
46. Practice Exercises – Beginner
Exercise 1
Print numbers from 1 to 10 using Do Until.
Exercise 2
Print numbers from 10 to 1 using Do Until.
Exercise 3
Print all even numbers from 2 to 20.
Exercise 4
Print all odd numbers from 1 to 19.
Exercise 5
Calculate the sum of numbers from 1 to 100.
Exercise 6
Calculate the multiplication table of 7.
47. Practice Exercises – Intermediate
Exercise 7
Read column A until a blank cell is found.
Exercise 8
Copy column A into column B until a blank cell is found.
Exercise 9
Convert customer names into uppercase until a blank row.
Exercise 10
Find the first occurrence of "Pending".
Exercise 11
Stop processing when "STOP" is found.
Exercise 12
Ask the user to enter a number greater than 100. Continue asking until the user enters a valid number.
48. Practice Exercises – Advanced
Exercise 13
Read sales from column A until the total reaches ₹1,00,000.
Exercise 14
Search for a customer and display the row number.
Exercise 15
Process employee records until either a blank cell or STOP is found.
Exercise 16
Classify sales as VIP, Good or Normal.
Exercise 17
Generate invoice numbers INV-0001 to INV-0100.
Exercise 18
Create a nested Do Until loop to generate a multiplication table from 1 to 10.
49. Mini Project – Employee Report Automation
Suppose your worksheet contains:
| Column | Data |
|---|---|
| A | Employee Name |
| B | Department |
| C | Salary |
| D | Result |
Write a macro that:
- Starts from row 2.
- Processes rows until column A is blank.
- If salary is greater than or equal to 100000, write "High".
- If salary is greater than or equal to 50000, write "Medium".
- Otherwise write "Low".
- Continue until the last employee.
Solution
Option Explicit
Sub EmployeeSalaryReport()
Dim ws As Worksheet
Dim i As Long
Set ws = ThisWorkbook.Worksheets("Data")
i = 2
Do Until ws.Cells(i, 1).Value = ""
If ws.Cells(i, 3).Value >= 100000 Then
ws.Cells(i, 4).Value = "High"
ElseIf ws.Cells(i, 3).Value >= 50000 Then
ws.Cells(i, 4).Value = "Medium"
Else
ws.Cells(i, 4).Value = "Low"
End If
i = i + 1
Loop
MsgBox "Employee report completed."
End Sub
50. Practical Quiz – Do Until Loop
Question 1: What does Do Until mean?
A. Continue while the condition is True
B. Continue until the condition becomes True
C. Execute only once
D. Stop immediately
Do Until continues executing until its condition becomes True.
Question 2: Which syntax is correct?
A.
Do Until condition Loop
B.
Until Do condition Loop
C.
Do condition Until Loop
D.
Loop Until condition Do
Question 3: Where is the condition checked in Do Until...Loop?
A. At the beginning
B. At the end
C. Never
D. Only after an error
Question 4: Where is the condition checked in Do...Loop Until?
A. Beginning
B. End
C. Middle
D. Before Sub starts
Question 5: Which loop can execute zero times?
A. Do Until...Loop
B. Do...Loop Until
C. Both always execute once
D. Neither
Question 6: Which loop executes at least once?
A. Do Until...Loop
B. Do...Loop Until
C. Neither
D. For Each only
Question 7: What is the output?
Dim i As Long
i = 1
Do Until i > 3
Debug.Print i
i = i + 1
Loop
A. 1 2 3
B. 1 2
C. 0 1 2 3
D. Infinite loop
The values printed are 1, 2 and 3.
Question 8: What causes an infinite Do Until loop?
A. The condition never becomes True
B. Using Long
C. Using Cells
D. Using Debug.Print
Question 9: Which statement exits a Do loop immediately?
A. Stop Do
B. Exit Do
C. Break Do
D. End Loop
Question 10: What is commonly used for an Excel row counter?
A. Integer
B. Long
C. Boolean
D. Date
Question 11: Which condition can stop processing when column A is blank?
A.
Do Until Cells(i,1).Value = ""
B.
Do Until Cells(i,1).Value <> ""
C.
Do Until Cells(i,1)
D.
Do Until Blank
Question 12: What does Exit Do do?
A. Restarts the loop
B. Exits the current Do loop
C. Exits Excel
D. Exits the workbook
Question 13: Which operator requires both conditions to be True?
A. Or
B. And
C. Not
D. Like
Question 14: Which operator allows either condition to be True?
A. And
B. Or
C. Not
D. Is
Question 15: What is the purpose of increasing i inside the loop?
A. To change the worksheet name
B. To allow the loop condition to eventually change
C. To close Excel
D. To create a variable
Question 16: What does this condition mean?
Do Until i > 100
A. Stop when i becomes greater than 100
B. Stop when i becomes less than 100
C. Always execute 100 times
D. Never execute
Question 17: Which code checks for the word STOP?
A.
Do Until Cells(i,1).Value = "STOP"
B.
Do Stop Cells(i,1)
C.
Until Cells(i,1)
D.
Stop Until
Question 18: What is a nested loop?
A. A loop inside another loop
B. A loop with no condition
C. A loop with an error
D. A loop that cannot stop
Question 19: Which is better for Excel row counters?
A. Long
B. Boolean
C. String
D. Date
Question 20: What should you do if a Do Until loop appears to run forever?
A. Check whether the stopping condition can become True
B. Close Excel immediately
C. Delete the macro
D. Change Long to String
Use breakpoints and Debug.Print to inspect the condition and variables.
51. Do Until Loop – Interview Questions
- What is a Do Until Loop in VBA?
- What is the difference between Do Until and Do While?
- What is the difference between Do Until...Loop and Do...Loop Until?
- Can Do Until execute zero times?
- Which Do loop executes at least once?
- What is Exit Do?
- How do you process Excel rows until a blank cell?
- How do you stop a loop when a specific value is found?
- How do you avoid an infinite loop?
- Why is Long preferred for Excel row counters?
- How do you use And and Or with Do Until?
- How do you search an Excel range using Do Until?
- Can Do Until be nested?
- How can you debug an infinite loop?
- When would you choose Do Until instead of For...Next?
52. Do Until Cheat Sheet
| Code | Meaning |
|---|---|
Do Until condition
|
Continue until condition becomes True. |
Loop
|
End of Do Until loop. |
Do...Loop Until condition
|
Check condition at the end. |
Exit Do
|
Exit the current Do loop immediately. |
And
|
Both conditions must be True for the combined condition to be True. |
Or
|
At least one condition must be True for the combined condition to be True. |
53. When Should You Use Do Until?
| Situation | Recommended Loop |
|---|---|
| You know exactly how many times to repeat | For...Next |
| You want to process every object | For Each |
| You want to continue while a condition is True | Do While |
| You want to continue until a condition becomes True | Do Until |
| You want to process rows until blank | Do Until |
| You want to stop when a value is found | Do Until + Exit Do |
54. Final Summary
Do Until...Loop
Do Until condition
'Code
Loop
The condition is checked at the beginning.
It can execute zero times.
Do...Loop Until
Do
'Code
Loop Until condition
The condition is checked at the end.
It executes at least once.
55. The Most Important Rule to Remember
DO UNTIL "Keep executing until the condition becomes TRUE."
For example:
Do Until i > 10
Debug.Print i
i = i + 1
Loop
Think:
"Keep going until i becomes greater than 10."CHIRAGCODER VBA Learning Tip
Do not only read the examples. Open Excel VBA Editor and type them yourself.
Learn ↓ Type ↓ Run ↓ Observe ↓ Debug ↓ Modify ↓ Practice ↓ Build Real Project
The best way to learn VBA is to convert each example into a real Excel automation problem.
Smarter Work Beats Hard Work.
0 Comments