While
Statement
Executes a sequence of statements while a given condition is true.
Syntax
While condition
[ statements ]
End [ While ]
Parts
condition
- Mandatory expression of the type
Boolean
. statements
- Optional one or more executable statements.
They execute while
condition
is true. - The alternative is two or more groups of statements.
The first group starts with
Begin
, and executes the same as specified above. The subsequent groups start withWhen
, and execute after the end of the loop. SeeWhen
statements below for more information. End
- Completes the statement.
You can also use
End While
. - You can change this part of the syntax.
See
@Option
Directive for more information.
Instructions
End While
is not the same as Exit While
.
Use the construct While
when you must execute one or more statements again and again.
It is recommended when you cannot be sure how many times the statements must execute.
Control is connected with the Boolean condition
after While
.
Other loop constructs are possibly more flexible or can give better performance.
See the See also section below for more information.
Usual execution
If condition
is true, statements
execute.
After End
, control moves back to While
, where condition
calculates again.
If condition
stays true, statements
continue to execute.
If it becomes false, control moves to the statement after End
.
While
always calculates condition
before statements
execute.
If condition
is initially false, statements
do not execute.
Exit While
The statement Exit While
can stop While
.
Exit While
immediately moves control to the statement after End
.
When
statements
To find if While
completed because condition
became false, use When Done
.
To find if While
was not executed because condition
was initially false, use When None
.
See Begin…When
Statements for more information.
Examples
Dim counter = 5
Dim factorial = 1
While counter > 0
factorial *= counter
Counter -= 1
End While
See also
- Do…Loop Statement – Is more flexible in the location of the condition.
- For Statement – Gives better performance for execution a specified number of times.
- Begin…When Statements
- Exit Statement
- Loop Constructs