How to Use Excel VBA Do While Loop with Multiple Conditions

Excel VBA provides a robust set of tools for automating tasks and manipulating data. One essential feature is the Do While loop, which allows you to execute code repeatedly as long as a specified condition remains true. But what if you need to incorporate multiple conditions within the loop? In this article, we will explore how to harness the full potential of the Do While loop by incorporating multiple conditions using Excel VBA. We will cover the syntax, logical operators, and best practices to create efficient and flexible loops that can handle complex conditions. Whether you’re a beginner or an experienced VBA programmer, mastering the use of multiple conditions in Do While loops will significantly enhance your ability to automate tasks and solve intricate problems in Excel. So let’s dive in and unlock the power of the Do While loop with multiple conditions in Excel VBA.

Overview image of VBA Do While loop with multiple conditions


 


Syntax of Do While Loop In VBA

Here’s an explanation of each part of the syntax:

Do While – The loop keyword is used to start the loop. It specifies that the loop will be executed while a certain condition is true.

Condition – The condition that determines whether the loop should continue or exit. It is a logical expression that evaluates to either True or False. If the condition is True, the loop body is executed. If it’s False, the loop is exited.

Statements – The code that is executed repeatedly as long as the condition is true. This can be any valid VBA code, including assignments, calculations, or function calls.

Loop – The keyword used to mark the end of the loop. After the Loop statement, the program returns to the Do While statement to check the condition again.

Do While
 <condition>
    <statements>
Loop

Syntax of Do While loop


Excel VBA Do While Loop with Multiple Conditions: 3 Suitable Approaches

In this article, we will explore three suitable approaches to using a Do While Loop with multiple conditions in Excel VBA. These approaches will help you achieve various tasks efficiently by evaluating multiple conditions simultaneously within the loop.


1. Finding Total Numbers Using VBA Do While Loop with Multiple Conditions

Here we are going to sum numbers from 1 to 10 by using VBA Do While Loop with multiple conditions.

Let’s follow the following instructions, to sum up the numbers:

  •  Click here to see how to launch VBA and insert a Module in Microsoft Excel
  • After launching the VBA and inserting a module. Paste the below code:
Sub ExampleDoWhileLoop()
    Dim i As Integer
    Dim total As Integer
    i = 1
    total = 0
    Do While i <= 10 And total + i < 50
        total = total + i
        i = i + 1
    Loop
    MsgBox "The total is: " & total
End Sub
  • We made multiple conditions. The first one is i<=10 which means the number is not more than 10 and the second condition is total+i<50, which indicates the total number should not exceed 50.
  • Now run the code by pressing the F5 key or by clicking on the play button to see the result.

Finding total numbers using VBA Do While loop 

  • The outcome is 45.
  • The total outcome of 1 to 10 should be 55. But because of the second condition, the outcome is showing 45.

The output of total numbers

Read More: How to Run Excel VBA Do While Loop till Cell Is Not Empty


2. Coloring Multiple Cells Utilizing VBA Do While Loop with Multiple Conditions

We can specify the number of conditions in this process and use the Do While Loop code accordingly. It will give us the required solution.  To show the process, we take a dataset that includes the Student’s name, Student ID, and Number. Follow the steps carefully. Here, we will format the cells with color based on the number greater than or equal to 80.

Dataset of some students’ score

  •  Launch VBA and insert a Module in Microsoft Excel
  • Now, write down the following code:
Sub Do_While_Loop2()
Dim i As Integer
i = 5
Do While i <= 13
If Range("D" & i).Value >= 80 Then
Range("D" & i).Interior.Color = RGB(204, 255, 0)
End If
i = i + 1
Loop
End Sub
  • After that, click on the Play button or press F5.

Pasting VBA code into the module

  • As a result, we will get the desired solution for multiple conditions. See the screenshot below.

Colored cell after applying VBA code


3. Including an IF Statement in a Do While Loop for Multiple Layer of Conditions

In the below example, we are going to show utilizing the Do While loop with multiple conditions and also including the IF statement there. We’ll find the even numbers within a range.

  • Launch VBA and insert a Module in Microsoft Excel
  • In the Module paste the following code:
Sub FindEvenNumbers()
    Dim i As Integer
    Dim evenNumbers As String
    i = 1
    Do While i <= 10
        If i Mod 2 = 0 Then
            evenNumbers = evenNumbers & " " & i
        End If
        i = i + 1
    Loop
    MsgBox "Even numbers in the range:  " & evenNumbers
End Sub
  • Now run the code by pressing the F5 key or by clicking on the play button to see the result.

Applying to Do While loop including IF statement

  • You can see the even numbers between 1 and 10 as an output.

The output of even numbers


How to Use a Do While Loop in VBA

Here we are going to discuss applying to Do While Loop with just a single condition. We will input only criteria here while writing the code. In this section, we will try to find out the total numbers from 1 to 10.

To accomplish this task

  • Launch the VBA and insert a Module in Microsoft Excel.
  • Then paste the following code
Sub ExampleDoWhileLoop()
    Dim i As Integer
    Dim output As String
    i = 1
    Do While i <= 10
        ' Concatenate the output with current i value
        output = output & " " & i
        ' Increment the i
        i = i + 1
    Loop
    ' Display the output in a message box
    MsgBox output
End Sub
  • Click on the Play button or press F5 to run the code.

Applying VBA Do While loop code with a single condition

  • Now you can able to all the numbers as an output from 1 to 10.

Output numbers from 1 to 10


Things to Remember

  • Syntax: Ensure that you follow the correct syntax for the Do While loop in VBA. The loop starts with the Do While statement, followed by the condition, and ends with the Loop statement.
  • Condition order: Pay attention to the order of conditions in your Do While loop. The conditions should be arranged in a logical order that makes sense for your program’s requirements.
  • Exit condition: Make sure to include an exit condition in your loop. The loop can run indefinitely without an exit condition, causing your program to become unresponsive or result in an infinite loop.
  • Logical operators: Use logical operators such as And, Or, and Not to combine or negate conditions as needed. These operators help you create complex conditions by evaluating multiple expressions.
  • Condition evaluation: Ensure that the conditions in the Do While loop are properly evaluated. Double-check the logical operators, relational operators, and variables used in the conditions to ensure they are correctly implemented.
  • Testing and debugging: It’s recommended to test and debug your code to verify that the loop conditions and code execution are working as expected. Step through the code using breakpoints or add debug output to ensure the loop behaves as intended.

Frequently Asked Questions

  • How do I use multiple if conditions in VBA?

To test multiple conditions, combine the VBA IF statement with the AND operator. When you utilize it, you can test two conditions at once and determine whether both of them are true. And the result is returned as false if any of the conditions is true.

  • How many times can I do a while loop?

In VBA, the number of times you can execute a Do While loop depends on the condition you specify. As long as the condition remains true, the loop will continue to execute. There is no inherent limit on the number of iterations you can have in a Do While loop.

  • How do you write two conditions in a for loop in VBA?

In VBA, you can use the For…Next loop to iterate over a range of values. If you want to include two conditions in the loop, you can combine them using logical operators (And, Or) within the loop’s condition.


Download Practice Workbook

If you want a free copy of the illustrated workbook we discussed during the presentation, please click the link below this section.


Conclusion

In this article, we have explored the capabilities of the Do While loop with multiple conditions in Excel VBA. By incorporating multiple conditions, we can create dynamic and flexible loops that adapt to various scenarios and data conditions. Please leave any questions or comments in the space provided below.


Related Articles

Get FREE Advanced Excel Exercises with Solutions!

Tags:

Mizbahul Abedin
Mizbahul Abedin

Md Mizbahul Abedin, BSc, Textile Engineering and Management, Bangladesh University of Textiles, has been working with the ExcelDemy project for 11 months. Currently working as an Excel and VBA Content Developer who provides authentic solutions to different Excel-related problems and writes amazing content articles regularly. He has published almost 20 articles in ExcelDemy. He has passions for learning new things about Microsoft Office Suite and Data analysis. Besides, he also likes to travel, photography, international politics, and read... Read Full Bio

We will be happy to hear your thoughts

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo