Begin…When Statements

Execute a different block of code given what the loop does.

Syntax

start_clause
  Begin [ identifier_list ]
    [ loop_statements ]
  When { identifier | NONE | DONE | Else }
    [ after_statements ]
  …
end_clause

Parts

start_clause
Mandatory start clause for one of the loop constructs: Do, For, For Each, or While.
Begin
Mandatory keyword.
identifier_list
Optional one or more identifiers with a comma between each.
loop_statements
Optional statements that execute again and again.
When
Mandatory one or more times
identifier
Mandatory for each identifier in identifier_list. Specifies the start of statements that execute after “Exit identifier”.
NONE
Specifies the start of statements that execute when loop_statements did not execute.
DONE
Specifies the start of statements that execute when loop_statements completed.
Else
Specifies the start of statements that execute when one of the conditions, NONE or DONE, are true. If you use Else, then you cannot use NONE or DONE.
after_statements
Optional executable statements.
end_clause
Mandatory end clause for its related start clause (start_clause).

Instructions

When identifier

If you use When identifier in a loop construct, then the statements in this block of code execute because of Exit identifier.

When DONE

If you use When DONE in a loop construct, then the statements in this block of code execute only when the loop stops as usual. The statements execute at most one time for each loop, almost the same as code not in the loop.

If a loop stops because of Exit or Return, then When DONE does not execute. Thus execution continues as usual for the given statement.

When NONE

If you use When NONE, then the statements in this block of code execute only when the body of the loop did not execute. A table that summarizes the conditions in which this can occur follows.

Loop constructLoop body not executed
While C
When condition C is initially false
Do While C
When condition C is initially false
Do Until C
When condition C is initially true
For I = A To B [ Step D ]
When A > B for a positive D. Or A < B for a negative D
For Each I In G
When group G is #Null or is empty

Note: You cannot use When NONE in Do…Loop While and Do…Loop Until because they execute their statements a minimum of one time.

When Else

If you use When Else in a loop, then it is the same as When DONE and When NONE put together.

Scope

The scope of variables in these blocks is the same as variables in the usual loop construct. Thus you cannot use variables declared in them after the end of the loop.

Examples

When identifier

For Each name$ In names$()
  Begin found
    If name$ = match$ Then Exit found
  When found
    PrintLine "Match found."
  When DONE
    PrintLine "No matches found."
End For

See also