The VBA GoTo statement helps code execution jump to a specific line within the procedure. In simple words, with the goto statement, VBA jumps to a particular line that you specify. For example, if you specify to jump to the second line, GOTO will jump to that line.
How to use VBA GoTo Statement in a Code
- First, you need to use the goto statement.
- After that, you need to define the place where you want to VBA to jump from goto.
- Next, create the tag to create that place in the procedure.
- In the end, add the line(s) of code that you want to get executed.
Sub vba_goto()
GoTo Last
Range("A1").Select
Last:
Range("A12").Select
End Sub
GoTo to Repeat a Code
You can also use the go-to statement to repeat a code using a set of conditions.
Sub goto_repeat()
Dim iMessage As String
' Declares a variable to store the user's input as a string.
Question:
' This is a label used for the GoTo statement to reference.
iMessage = InputBox("What's the day today?")
' Displays an input box prompting the user to input the current day.
' The input is stored in the iMessage variable.
If iMessage <> "tuesday" Then
' Checks if the user's input is not equal to "tuesday".
MsgBox "Wrong answer, try again."
' If the input is not "tuesday", this message box is shown to inform the user.
GoTo Question
' Sends the program back to the 'Question' label, prompting the user to try again.
Else
' If the input is equal to "tuesday", the following block of code runs.
MsgBox "That's the right answer."
' Displays a message box indicating the correct answer was given.
End If
' End of the If-Else condition.
End Sub
When you run the above code, it asks you for the day’s name, and if you enter anything other than “Tuesday,” it will repeat the question. If you look at the code, you can see we have to use the goto and if statements.
Now, when the user enters anything other than the right answer, the goto statement makes VBA repeat the code. (But whenever you use these sorts of codes, you need to be extra cautious as they can create an endless loop.
VBA GoTo End
You can also exit a sub using the goto statement.
In the above code, we have used the “last” tag just before the end statement. When VBA reaches the GoTo statement, it jumps to the “Last” at the end of the procedure.
GoTo Statement to go to a Line in Another Sub Routine
Well, the go-to statement is quite handy for making VBA jump from one place to another, but it’s not possible to make it go to another procedure in the module.