|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
While...End While Statement (Visual Basic)
Runs a series of statements as long as a given condition is True.
Use a While...End While structure when you want to repeat a set of statements an indefinite number of times, as long as a condition remains True. If you want more flexibility with where you test the condition or what result you test it for, you might prefer the Do...Loop Statement (Visual Basic). If you want to repeat the statements a set number of times, the For...Next Statement (Visual Basic) is usually a better choice.
If condition is True, all of the statements run until the End While statement is encountered. Control then returns to the While statement and condition is again checked. If condition is still True, the process is repeated. If it is False, control passes to the statement following the End While statement.
Nature of Condition. The condition usually results from a comparison of two values, but it can be any expression that evaluates to a Boolean Data Type (Visual Basic) value (True or False). This includes values of other data types, such as numeric types, that have been converted to Boolean.
Testing the Condition. The While statement always checks the condition before it begins the loop. Looping continues while the condition remains True.
Number of Iterations. If condition is False when you first enter the loop, it does not run even once.
Nesting Loops. You can nest While loops by placing one loop within another. You can also nest different kinds of control structures within one another. For more information, see Nested Control Structures.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement following the End While statement. You might want to exit a loop if you detect a condition that makes it unnecessary or impossible to continue iterating, such as an erroneous value or a termination request. You can place any number of Exit While statements anywhere in the While loop. Exit While is often used after evaluating some condition, for example in an If...Then...Else structure.
Endless Loops. One use of Exit While 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 you detect such a condition, you can use Exit While to escape the loop. For more information, see Do...Loop Statement (Visual Basic).
This example uses the While...End While structure to increment a counter variable. The statements in the loop run as long as the condition evaluates to True.