On...GoSub Statement

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

Syntax

On expression GoSub destinationlist

The On...GoSub statement syntax has these parts:

Part Description
expression Required. Any numeric expression that evaluates to a whole number between 0 and 255, inclusive. If expression is any number other than a whole number, it is rounded before it is evaluated.
destinationlist Required. List of line numbers or line labels separated by commas.

Remarks

The value of expression determines which line is branched to in destinationlist. If the value of expression is less than 1 or greater than the number of items in the list or greater than 255 then control drops to the statement following On...GoSub.

You can mix line numbers and line labels in the same list.

    Tip: Select Case provides a more structured and flexible way to perform multiple branching.

Example

Sub OnGosubDemo()
Dim Number, MyString

MyString = "Nothing"
Number = InputBox("Enter branch number:") ' Initialize variable.
' Branch to Sub<Number>.
On Number GoSub Sub1, Sub2

Trace MyString

Exit Sub
Sub1:
MyString = "In Sub1" : Return
Sub2:
MyString = "In Sub2" : Return
End Sub

 

See Also

GoSub...Return Statement, GoTo Statement, On...GoTo Statement, Select Case Statement