GoSub

The GoSub statement is used to jump to a location in code specified by a label or line number within the current procedure and then return to the previous position and continue execution. Using the GoSub statement is not necessary. Separate subroutines can be used instead of GoSub...Return and the Select Case statement can be used instead of On...GoSub.

GoSub...Return

GoSub...Return is used to jump to a label or line number, execute code, and then return to the previous position in code and continue execution. Creating separate procedures may provide more structure and is more conventional than using GoSub...Return.

Public Sub Example()

    Debug.Print "Hello"

    GoSub ExampleSub

    Debug.Print "Goodbye"

    Exit Sub

ExampleSub:
    Debug.Print "Hello From ExampleSub"
    Return

End Sub

On...GoSub

On...GoSub can be used to jump to labels or line numbers based on the result of a numeric expression that evaluates to a number between 0 and 255, execute some code, and then jump back to the previous position using the Return statement. Using Select Case is a more structured way of branching.

Syntax: On expression GoSub sub1, sub2, ...

Public Sub Example()

    Dim Num As Byte
    Num = 2

    On Num GoSub Sub1, Sub2, Sub3

    Debug.Print "Exiting Sub"
    Exit Sub

Sub1:
    Debug.Print "Sub1"
    Return
Sub2:
    Debug.Print "Sub2"
    Return
Sub3:
    Debug.Print "Sub3"
    Return

End Sub
Public Sub Example()

    Dim Num As Byte
    Num = 2

    On Num GoSub 10, 20, 30

    Debug.Print "Exiting Sub"
    Exit Sub

10  Debug.Print "Line 10"
    Return

20  Debug.Print "Line 20"
    Return

30  Debug.Print "Line 30"
    Return

End Sub