GoSub...Return Statement

Description

Branch to and return from a subroutine within a procedure.

Syntax

GoSub line
. . .
line
. . .
Return

The line argument can be any line label or line number.

Remarks

You can use GoSub and Return anywhere in a procedure, but GoSub and the corresponding Return must be in the same procedure. A subroutine can contain more than one Return statement, but the first Return statement encountered causes the flow of execution to branch back to the statement immediately following the most recently executed GoSub statement.

Note

You can't enter or exit Sub procedures with GoSub...Return.

Tip

Creating separate procedures which you can call may provide a more structured alternative to using GoSub...Return.

See Also

End Statement; GoTo Statement; On...GoSub, On...GoTo Statements; Sub Statement.

Example

This example uses GoSub to call a subroutine within a Sub procedure. The Return statement causes the execution to resume at the statement immediately following the Gosub statement. The Exit Sub statement is used to prevent control from accidentally flowing into the subroutine.


Sub GosubDemo()
    Num = 10    ' Initialize variable.
    GoSub MyRoutine    ' Branch to subroutine.
    Debug.Print Num    ' Print value upon return.
    Exit Sub    ' Exit Sub procedure.
MyRoutine:    ' Start of subroutine.
    Num = Num \ 2    ' Halve the value.
    Return    ' Return from subroutine.
End Sub