VBA GoTo statement helps code execution to jump to a specific line within the procedure. In simple words, with the goto statement, VBA jumps to a particular line that is specified by you. For example, if you have specified to jump to the second line go 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 condition.
Sub goto_repeat() Dim iMessage As String Question: iMessage = InputBox("what's the day today?") If iMessage <> "tuesday" Then MsgBox ("wrong answer, try again.") GoTo Question Else MsgBox ("that's the right answer.") End If End Sub
When you run the above code it asks you for the day 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 statement and the if statement.
Now when the user enters anything other than the right answer, the goto statement makes VBA repeat the code. (but whenever you are using these sorts of codes you need to be extra cautious as it 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 and when VBA reaches the GoTo statement, it makes VBA jump to the “Last” at the end of the procedure.
GoTo Statement to go to a Line in Another Sub Routine
Well, go to statement as quite handy to make VBA jump from one place to another, but it’s not possible to make it go to another procedure in the module.