VBA Do While Loop

VBA Do while is a loop in which you have to specify a condition, and that condition must be true for the loop to run. In other words, it first checks whether the condition you’ve specified is true, and if it is true, it runs the loop, and if it is false, it does nothing.

It tests the condition in each iteration and then executes the statement. For example, if you need to add worksheets to Excel, but the total count of the worksheets is 12 or lower. In this case, you can write the code using the do-while loop.

NOTE: “The Do … Loop While Statements” check the condition at the end of the Loop.

We have two types of syntax in the Do while loop. So, let’s check on the two types:

Do While… Loop Statement

The while condition is checked first before any code block is executed.

Syntax 1

Do While condition

[statement 1]

[statement 2]

...

[statement n]

[Exit Do]

[statement 1]

[statement 2]

...

[statement n]

Loop

Syntax 2

Do… While Loop Statement

There is an alternate Syntax for Do…while loop. The code block is executed first and then the while condition is checked.

Do

[statement 1]

[statement 2]

...

[statement n]

Loop While [Condition]

Flow Diagram

Do While Condition

Example 1

It tests for the condition in each iteration and then executes the statement. For example, suppose you want to show a MesgBox with “i” Count numbers in Excel when the total numbers of the “i” Count is 10. In this case, you can write the code using the do-while loop.

Below is the VBA code that will run this Do While loop and then show the result in a message box.

Sub VBADoWhileLoop_Example1()

Dim i As Integer

i = 1

Do While i <= 10

MsgBox i

i = i + 1

Loop

End Sub

The stated loop continues to work until the value of ‘i’ becomes 10. Immediately the loop becomes 11, the loop ends (as the While condition becomes False).

See More: VBA Do Until Loop

Example 2

we will use Do…while loop to check the condition at the end of the loop in this example. The statements inside the loop should execute at least once, even if the condition is False.

Sub VBADoWhileLoop_Example2()

Dim i As Integer

i = 0

Do

i = i + 1

Loop While i < 5

MsgBox "Value of i is : " & i

End Sub

After the execution of the code, you will get the following output.

MsgBox

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top