On...GoSub, On...GoTo Statements

See AlsoBMCEW9              Example4JWU9GZ>Low

Branch to one of several specified lines, depending on the value of an expression.

Syntax 1

On expression GoSub destinationlist

Syntax 2

On expression GoTo destinationlist


The On...GoSub, On...GoTo syntax has these parts:

Part                        Description


On                           Begins the On...GoSub or On...GoTo control structure.

expression               Any numeric expression71RISN 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 numbers18F50XF and line labelsGH72Z1 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:

Value                                                 Result


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.


See Also

GoSub...Return Statement3HAWIA

GoTo StatementGU57HD

Select Case StatementVCC4T3

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

End Sub