Search
Close this search box.

VBA Do While Loop


The Do While loop in VBA is a control flow statement that repeatedly executes a block of code as long as a specified condition remains True.

Explanation:

  1. Condition Check: The loop begins by checking the condition.
  2. Execution: If the condition is True, the code within the loop is executed.
  3. Optional Exit Do: You can use the Exit Do statement within the loop to exit the loop prematurely if a certain condition is met.
  4. Re-evaluation: After executing the code within the loop, the condition is checked again.
  5. Repetition: If the condition is still True, the code within the loop is executed again, and this process repeats.
  6. Termination: The loop continues to execute until the condition becomes False. Once the condition becomes False, the loop terminates, and the program continues to the next statement after the Loop keyword.

Syntax:

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

Example

				
					Sub CountToTen()
    Dim counter As Integer
    counter = 1

    Do While counter <= 10
        MsgBox counter
        counter = counter + 1
    Loop
End Sub
				
			

Above example:

  • The counter variable is initialized to 1.
  • The Do While loop checks if counter is less than or equal to 10.
  • If counter is less than or equal to 10, the MsgBox displays the current value of counter, and then counter is incremented by 1.
  • The loop continues until counter exceeds 10.

Example with Exit Do

				
					Sub FindNumber()
    Dim i As Integer
    i = 1

    Do While i <= 10
        If i = 5 Then
            Exit Do 
        End If
        MsgBox i
        i = i + 1
    Loop
End Sub
				
			

This code will display the numbers 1, 2, 3, and 4 in separate message boxes. When i reaches 5, the Exit Do statement will be executed, and the loop will terminate.

Key Points:

  • The Do While loop is useful when you need to execute a block of code repeatedly as long as a certain condition is met.
  • The Exit Do statement can be used to exit the loop prematurely under specific conditions.
  • The condition is checked at the beginning of the loop, so the code within the loop may not execute even once if the condition is initially False.