Skip to main content

GoSub...Return statement

Table of contents
  1. Syntax
  2. Remarks
  3. Example

Branches to and returns from a subroutine within a procedure.


GoSub line
... line
line ...

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


Use GoSub and Return anywhere in a procedure, but GoSub and the corresponding Return statement 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.


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()
    Dim Num
    ' Solicit a number from the user.
    Num = InputBox("Enter a positive number to be divided by 2.")
    ' Only use routine if user enters a positive number.
    If Num > 0 Then GoSub MyRoutine
    Debug.Print Num
    Exit Sub ' Use Exit to prevent an error.
    Num = Num / 2 ' Perform the division.
    Return ' Return control to statement.
End Sub ' following the GoSub statement.

Leave a comment

Your email address will not be published. Required fields are marked *

Format your code: <pre><code class="language-vba">place your code here</code></pre>