Open In App

How to Use Do While Loop in Excel VBA?

Last Updated : 09 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A Do....While loop in Excel VBA is used to repeat a set of statements as long as a given condition is true. This condition can be checked either at the start or at the end of the loop, depending on how you want the loop to behave.

Flowchart:

Uses of Do-While loop:

The Do While loop is used in two ways:

  • Do…while loop which checks the condition at the STARTING of the loop.
  • Do…while loop which checks the condition at the  END of the loop.

Syntax 1:

Do While condition
[statements]
[Exit Do]
[statements]
Loop

Syntax 2: 

Do While 
[statements]
[Exit Do]
[statements]
Loop condition

How to Implement a Do While loop:

Follow the below steps to implement a Do-While loop:

Step 1: Define a Macro

Private Sub Demo_Loop()
End Sub

Step 2: Define variables

j=2
i=1

Step 3: Write Do While Loop. You can write condition at the beginning or at the end

Do While i < 5

Step 4: Write statements to be executed in loop

msgbox "Table of 2 is : " & (j*i)
i=i+1

Step 5: End loop.

Now let's take a look at some of the examples.

Example 1: Do…while loop which checks the condition at the STARTING of the loop. The below example uses Do…while loop to check the condition at the starting of the loop. The statements inside the loop are executed, only if the condition is True. We will print Table of 2 using Do...while loop;

Private Sub Demo_Loop()
j=2
i=1
Do While i < 5
msgbox "Table of 2 is : " & (j*i)
i=i+1
Loop
End Sub

Output:

Example 2: Do…while loop which checks the condition at the  END of the loop. The below example checks the condition at the end of the loop. The major difference between these two syntax is explained in the following example.

Private Sub Demo_Loop()
i = 10
Do
i = i + 1
MsgBox "The value of i is : " & i
Loop While i < 3 'Condition is false.Hence loop is executed once.
End Sub

When the above code is executed, it prints the following output in a message box.

Output:

Conclusion

The Do While loop in Excel VBA is a powerful tool for repeating tasks until a condition fails. Whether you check the condition at the beginning or the end depends on whether you want to guarantee at least one execution of your code block. Mastering these loops will help you write cleaner, more efficient VBA code.


Article Tags :

Explore