Keyword

While...Wend


Description

Repeatedly executes a series of statements while a specified condition is True.

Usage

While Condition
  [ Statements ]
  [ Continue [ While ] ]
  [ Exit [ While ] ]
  [ Statements ]
Wend

Part

Description

While

Begins the loop. Condition is evaluated to determine if the loop should exit.

Condition

Any valid Boolean expression. When this expression evaluates to True, the loop will continue to execute.

Statements

Statements to be executed repeatedly until condition evaluates to False.

Continue

If a Continue statement is present, execution will skip over the remaining statements in the loop and resume with a new iteration of the loop.

Exit

If an Exit statement is present, execution of the loop is terminated and resumes with the next line following the loop.

Wend

Ends the loop.

Notes

If Condition is True, all statements are executed until the Wend statement is reached. If Condition is still True, the process is repeated. If Condition is False, then execution continues with the statement following the Wend statement.

While...Wend statements can be nested to any level. Each Wend statement goes with the previous While statement. It is permissible to place Var statements inside loops, including While loops.

If a variable is declared inside a While statement, it goes out of scope after the last iteration of the loop. For example,

Var i As Integer
While I < 100
  Var a As Integer
  a = i + 1
Wend
MessageBox(a.ToString) ' 'a' is out of scope

This loop makes sense with the variable "a" declared outside the loop.

When a loop runs, it takes over the interface, preventing the user from interacting with menus and controls. If the loop is very lengthy, you can move the code for the loop to a separate Thread, allowing it to execute in the background.

Sample code

This example uses the While...Wend statement to increment a variable.

Var x As Integer
While x < 100
  x = x + 1
Wend

Using Exit:

Const kAttempts = 10
Var attempt As Integer = 1
Var output As String

While attempt <= kAttempts
  Var randomValue As Integer = System.Random.InRange(1, 10)
  If randomValue > 5 Then
    output = "Found a random value above 5 after " + attempt.ToString + " iterations."
    Exit
  End If
  attempt = attempt + 1
Wend

If attempt > kAttempts Then
  output = "Found NO random value above 5 after " + kAttempts.ToString + " iterations."
End If

Using Continue:

Const kAttempts = 100
Var matchCount As Integer
Var attempt As Integer

While attempt < kAttempts
  attempt = attempt + 1
  Var randomValue As Integer = System.Random.InRange(1, 10)
  If randomValue <= 5 Then
    Continue
  End If
  matchCount = matchCount + 1
Wend

Var output As String
output = "Found " + matchCount.ToString + " random values above 5 within " + kAttempts.ToString + " iterations."

Compatibility

All project types on all supported operating systems.

See also

Continue, Do...Loop, Exit, For...Next statements; DesktopApplication, Thread classes.