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:
condition.condition is True, the code within the loop is executed.condition is evaluated again.condition is still True, the code within the loop is executed again, and this process repeats.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:
While...Wend loop is suitable for situations where the number of iterations is not known beforehand.While statement eventually becomes False to avoid an infinite loop.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.