You can use the While statement to execute a block of statements an indefinite number of times depending on the Boolean value of a condition. The statements are repeated as long as the condition is True. The condition usually results from a comparison of two values, but it can be any expression that evaluates to a Boolean value (True or False). This includes values of other data types, such as numeric types, that have been converted to Boolean.
The While statement always checks the condition before it begins the loop. Looping continues while the condition remains True.
In the following example, the
CheckWhile procedure tests the condition before it enters the loop. If
Number had been initialized to 6 instead of 10, the statements inside the loop would never run.
Sub CheckWhile() Dim Counter As Integer = 0 Dim Number As Integer = 10 While Number > 6 Number = Number - 1 Counter = Counter + 1 End While MsgBox("The loop ran " & Counter & " times.") ' Runs 4 times. End Sub
You can transfer out of a While statement by using the Exit While statement. One use of this is to test for a condition that could cause an endless loop, which is a loop that could run an extremely large or even infinite number of times. If the condition is True, use Exit While to escape. If the condition is False, the loop continues running.
In the following example,
Number is assigned a value that could cause the loop to execute more than 2 ^ 31 times. The If statement checks for this and exits if it exists, preventing endless looping.
Sub ExitWhileExample() Dim Counter As Integer = 0 Dim Number As Integer = 8 While Number <> 10 If Number < 0 Then Exit While Number = Number - 1 Counter = Counter + 1 End While MsgBox("The loop ran " & Counter & " times.") ' Runs 9 times. End Sub
Note To stop an endless loop, press ESC or CTRL+BREAK.