Excel VBA GoTo Statement

GoTo Statement

he GoTo statement branches unconditionally to a specified line in a procedure. It is used to transfer the program control to a new statement, which is headed by a label. It sends your program wherever you want. The statement is useful in controlling program flow, and it’s easy to create.

GoTo statement cannot be used to branch from outside a For...Next, For Each...Next, With...End With, SyncLock...End SyncLock, Try...Catch...Finally, or Using...End Using construction to a label inside.

GoTo statements are used when you wish to force the user to select any specific option. It functions as a loop and repeats the same stamen again and again unless the user uses another option.

Syntax

GoTo line

Parameter

Line (required) – This parameter represents any line label.

Example 1

Sub Goto_Exercise()
 Jmp:
 MB = MsgBox("Do you like Excel?", vbYesNo)
     If MB = vbYes Then
         MsgBox "Wow! I also like working on Excel!"
     Else
         MsgBox "Ohh! Try once and you will surely like it."
     GoTo Jmp:
     End If
 End Sub 

Output

Press F5 to run the output. As soon as, VBA code run, a msgbox will pop up, asking a question, “Do you like VBA?” with buttons, Yes or No option (as shown below).

GoTo Statement vba

We will choose the “No” option. Another msgbox pops up.

Another msgbox pops up

As soon as you will click on OK. The program jumps again to the first Msgbox, stating, “Do you like VBA?”. This will continue if you will click on No option. If you select the Yes option, another Msgbox will pop up (as shown below).

Msgbox, stating

As soon as you click OK, the program terminates.

While entering any password, if you type the wrong password, you notice the Input box appears over again till the time you enter the correct one. This can be done with VBA GOTO as well.

Example 2

Sub Goto_Exercise2()
 IB_Name = InputBox("Enter your Name: ")
 Jmp:
 IB_Pass = InputBox("Enter your password")
     'if the password does not match with Bill Gates
     'it will goto Wrong Pass section
     If IB_Pass <> "Bill Gates" Then GoTo WrongPass
         MsgBox "Welcome " + IB_Name + "You are eligible to run the program"
     Exit Sub    
 WrongPass:
     MsgBox "Sorry! Try again, Username and password do not match!"
     GoTo Jmp
 End Sub 

Output

As you will run the code. An InputBox will pop out, asking for your name. Type your name and click OK.

Once you submit the name, another box appears asking for your password.

you submit the name

If your password matches with “Bill Gates” a MsgBox will appear stating your eligibility. Else for the wrong password, it will intimidate you and again ask for the right password.

MsgBox will appear stating your eligibility
excel vba go to statement
excel vba go to statement1
VBA Excel Go to Statement