Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 57

Mastering Do...While Loops

Recommended resources

Welcome back! In our previous lesson, you learned how to programmatically control cell formatting to give your automated reports a professional and polished appearance. This is a vital skill for creating presentable financial statements and analyses.

In this lesson, we will complete our tour of VBA's core programming structures by exploring the Do...While loop. You've already mastered the For...Next loop, which is perfect for repeating actions a known number of times. The Do...While loop, however, gives you the power to repeat actions until a specific condition is met, even when you don't know in advance how many repetitions are needed. This is essential for processing real-world accounting data, which often varies in length.

For Loops vs. Do Loops: Knowing When to Use Each

Let's start by clarifying the fundamental difference between the two main types of loops in VBA.

  • A For...Next loop is used when you know exactly how many times you want the loop to run. For example, "process the next 12 months of data" or "format the first 10 rows of a report." The number of iterations is defined at the start.

  • A Do loop is used when the number of iterations is unknown. The loop continues based on a condition that is checked with each pass. This is ideal for tasks like, "process all transactions until you reach a blank row" or "keep asking the user for input until they enter a valid account code."

The Excel Macro Mastery guide provides an excellent explanation of this distinction.

VBA While Loop - A Complete Guide

This article clearly contrasts For loops and Do loops, which is the foundational concept for this lesson.

Please read the section titled For Loops Versus Do While Loops. It explains that For loops are for a known number of repetitions, while Do loops run while or until a condition is true.


The Anatomy of a Do...While Loop

The most common structure for this type of loop is Do While...Loop. The logic is straightforward: VBA checks a condition at the beginning of the loop. If the condition is True, the code inside the loop is executed. It then goes back to the top, checks the condition again, and repeats the process until the condition becomes False.

This flowchart illustrates the logic perfectly:

This flowchart shows the execution of a `Do While` loop. The condition is tested first (Step #1). If it's true, the statements are executed (Step #2), and the loop returns to check the condition again (Step #3). If the condition is false, the loop is exited.

The basic syntax looks like this:

Do While [condition]
    ' Code to be repeated goes here
Loop

The [condition] is simply a statement that VBA can evaluate as either True or False. For example, ActiveCell.Value <> "" is a condition that checks if the active cell is not empty.


Key Variations: Until, and Pre- vs. Post-Test Loops

The Do loop is flexible and has a few important variations you need to know. The following video from TrumpExcel provides a clear, step-by-step demonstration of these variations.

Free Excel VBA Course #17 - Do While and Do Until Loop in Excel VBA

This video effectively demonstrates the main syntax variations of the Do loop and shows the practical difference in their execution.

Please watch the following segments: First, watch the example of a basic Do While loop that checks the condition before executing. Notice how it processes cells until it finds a blank one. Next, observe the demonstration of a loop where the condition is checked after execution, from here. Pay close attention to the example where the starting cell is blank; it highlights why the loop still runs once. Finally, watch the explanation of the difference between While and Until. This clarifies that they are logical opposites.

Let's summarize the key points from the video and the Excel Macro Mastery guide.

  1. Do While vs. Do Until:

    • Do While [condition] runs as long as the condition is true.
    • Do Until [condition] runs up to the point the condition becomes true. They are two ways of saying the same thing, just with the logic inverted. For example:
      • Do While ActiveCell.Value <> "" (Loop while the cell is not empty)
      • Do Until ActiveCell.Value = "" (Loop until the cell is empty)
  2. Pre-test vs. Post-test: This refers to when the condition is checked.

    • Pre-test (Condition on Do line): Do While [condition] ... Loop
      The condition is checked before the loop's code runs. If the condition is initially false, the loop will not run at all (0 iterations). This is the most common and safest approach.
    • Post-test (Condition on Loop line): Do ... Loop While [condition]
      The code inside the loop is executed first, and then the condition is checked. This guarantees that the loop will always run at least once.

To solidify your understanding of all four combinations and what a "condition" is in VBA, let's turn back to the Excel Macro Mastery guide.

VBA While Loop - A Complete Guide

This guide provides clear tables and code examples to break down the syntax and logic of Do loops.

Please review the following sections: Conditions: Read the section on Conditions to see the comparison operators (=, <>, >, <) you'll use to build your loop criteria. Loop Formats: Read The Do Loop Format. This part explains the four main structures and the critical difference between checking the condition at the start versus the end. While vs. Until: Reinforce your understanding by reading the section While Versus Until, which uses plain English analogies.


Practical Application: Processing a List of Transactions

Now, let's see how you can combine a Do loop with other VBA concepts you've learned, like variables and If statements, to perform a realistic accounting task. The following video from WiseOwlTutorials demonstrates how to loop through a list of data, categorize it, and copy it to different worksheets—a process similar to separating transactions into different ledgers.

Excel VBA Introduction Part 15 - Do Until and Do While Loops

This video provides an excellent, in-depth example of using a Do Until loop for a practical data processing task relevant to your goals.

Watch the entire demonstration, from this more practical example to the end. As you watch, pay attention to how the Do Until loop forms the main structure, and inside it, the code: Reads a value from a cell into a variable. Uses an If...ElseIf...Else statement to categorize the data. Dynamically selects different worksheets based on the category. Copies and pastes the relevant data. Includes a best-practice tip by setting Application.ScreenUpdating = False to make the macro run faster.


Important Considerations: Exit Do and Infinite Loops

There are two final, crucial concepts to master for using Do loops safely and effectively.

1. Exiting a Loop Prematurely with Exit Do

Sometimes, you may need to stop a loop before its main condition is met. For example, if you are searching a list for a specific value, you can exit the loop as soon as you find it. The Exit Do statement allows you to do this, usually from within an If statement.

Do While ActiveCell.Value <> ""
    If ActiveCell.Value = "Stop Here" Then
        Exit Do ' Exit the loop immediately
    End If
    ' ... more code ...
    ActiveCell.Offset(1, 0).Select
Loop

2. Avoiding Infinite Loops

An infinite loop is a loop whose exit condition is never met. This causes your macro to run forever, freezing Excel. It's the most common pitfall with Do loops. It typically happens when you forget to include the code that works toward meeting the exit condition.

For example, in the code below, the value of counter never changes, so it will always be less than 10, and the loop will never end.

' DANGER: INFINITE LOOP!
Dim counter As Integer
counter = 1

Do While counter < 10
    ' Some action happens here...
    ' BUT we forgot to increase the counter!
    ' Missing line: counter = counter + 1
Loop

If you accidentally run an infinite loop, you can usually stop it by pressing Ctrl + Break on your keyboard.

The Excel Macro Mastery article gives a good summary of these points.

VBA While Loop - A Complete Guide

This final reading covers two essential practical topics for working with Do loops.

First, read the short section on Exit Do Loop. Then, carefully read the section on Infinite Loop. Understanding how to identify and deal with an infinite loop is a critical skill.


Conclusion

You have now added the versatile Do...While and Do...Until loops to your VBA toolkit. Unlike For...Next loops, they are the perfect tool for automating tasks where the amount of data is dynamic and unknown in advance—a common scenario in any accounting role. By mastering the different syntaxes and being mindful of potential infinite loops, you can write robust and flexible automation scripts.

Key Takeaways:

  • Use For...Next loops for a known number of iterations and Do loops when the number of iterations depends on a condition.
  • Do While loops continue as long as a condition is True.
  • Do Until loops continue until a condition becomes True.
  • Placing the condition on the Do line (pre-test) checks the condition before running, and the loop might not run at all.
  • Placing the condition on the Loop line (post-test) runs the code at least once before checking the condition.
  • Always ensure your loop includes a line of code that progresses toward meeting the exit condition to avoid an infinite loop.

In the next module, we will begin applying the loop structures and other VBA concepts you've learned to powerful, real-world data processing tasks, starting with how to write a macro to automatically clean data in a worksheet.