Do While Loop in Excel Vba

You are going to learn about programming do while loops. First, you are going to learn what loops are and why they are necessary. Then you are going to learn how to use a do while loop.

The ribbon

Click on the Developer tab and select View Code.

View Code

A new window (Visual Basic Editor) will open which will have a dialog box in the center. You will write the code in the dialog box.

New VBA Code

The code

Write the following line of code in the dialog box.

Sub loopexample()
Dim counter As Integer
counter = 1
Do While counter < 5
Cells(counter, "D").Value = counter
counter = counter + 1
Loop

After writing the code close the window by clicking on the cross(x) icon the the upper right side of the screen.

Explanation: In this code you have declared a variable counter of data type integer and has assigned the value 1 to it. You used the do while loop with the condition to count from 1 to 4 and store the value in cell D.

Example loop

After writing this code, close the window (visual basic editor) by clicking on the upper right cross button.

The result

This is the result. You have now successfully used a do while loop.

Sequence

See also  How to Add Hours to Time in Excel Vba