How to Use Do While Loop in Excel VBA?
A Do…While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop
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.
Do While condition [statements] [Exit Do] [statements] Loop
Do While [statements] [Exit Do] [statements] Loop condition
Implementing 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
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
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.
Attention reader! Don’t stop learning now. If you are an Excel beginner (or an intermediate) and want to learn Excel, Geeksforgeeks brings the perfect course for you to start, Diving Into Excel