GoSub...Return statement
Branches to and returns from a subroutine within a procedure.
Syntax
GoSub line
...
line
line ...
Return
The line argument can be any line label or line number.
Remarks
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.
Note
You can't enter or exit Sub procedures with GoSub...Return.
Tip
Creating separate procedures that you can call may provide a more structured alternative to using GoSub...Return.
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()
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.
MyRoutine:
Num = Num/2 ' Perform the division.
Return ' Return control to statement.
End Sub ' following the GoSub statement.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기