On...GoSub, On...GoTo Statements
See Also Example
Branch to one of several specified lines, depending on the value of an expression.
On expression GoSub destinationlist
On expression GoTo destinationlist
The On...GoSub, On...GoTo syntax has these parts:
On Begins the On...GoSub or On...GoTo control structure.
expression Any numeric expression that evaluates to a value between 0 and 255, inclusive. (The expression is rounded to an integer value before the On...GoSub or On...GoTo statement is evaluated.) The value of expression determines which of the lines in destinationlist the program branches to.
GoSub Causes program flow to branch to a subroutine within a procedure.
GoTo Causes program execution to continue at another place within a procedure.
destinationlist List of line numbers and line labels separated by commas..
If the value of expression is less than 1 or greater than the number of items in the list, one of the following results occurs:
Equal to 0 Program control drops to the next statement.
Greater than number of items in list Program control drops to the next statement.
Negative Illegal function call error is generated.
Greater than 255 Illegal function call error is generated.
You can mix line numbers and line labels in the same list. The number of line labels and line numbers you can use with On...GoSub and On...GoTo is limited only by the number you can physically fit on a single line.
Tip Select Case provides more structure and a more flexible way to perform multiple branching.
Select Case Statement
On...GoSub, On...GoTo Statement Example
The example uses On...GoSub to branch to one of two subroutines depending on user input. To try this example, paste the code into the Declarations section of a form. Then press F5 and click the form.
Sub Form_Click ()
Dim Msg, N ' Declare variables.
N = InputBox("Enter a number greater than 0 and less than 3.")
Msg = "You didn't follow directions." ' Error message.
On N GoSub Chose1, Chose2 ' Choose subroutine.
MsgBox Msg ' Display results.
Msg = "You chose 1." : Return
Msg = "You chose 2." : Return