Search
Close this search box.

VBA While Wend Loop


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

Explanation:

  1. Condition: The loop begins by evaluating the condition.
  2. Execution: If the condition is True, the code within the loop is executed.
  3. Re-evaluation: After executing the code within the loop, the condition is evaluated again.
  4. Repetition: If the condition is still True, the code within the loop is executed again, and this process repeats.
  5. 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 Wend keyword.

Syntax:

While condition
‘ Code to be executed as long as the condition is True
Wend

Example

				
					Sub CountToTen()
    Dim counter As Integer
    counter = 1

    While counter <= 10
        MsgBox counter
        counter = counter + 1
    Wend
End Sub
				
			

Key Points:

  • The While...Wend loop is suitable for situations where the number of iterations is not known beforehand.
  • Ensure that the condition within the While statement eventually becomes False to avoid an infinite loop.
  • You can use the Exit While statement to exit the loop prematurely under certain conditions.

Example with Exit While

				
					Sub FindNumber()
    Dim i As Integer
    i = 1

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

This code will display numbers from 1 to 4 and then exit the loop when i reaches 5.