GoTo statements

The most straightforward way to change the flow of a program is to use a GoTo statement. This statement simply transfers program execution to a new instruction, which must be preceded by a label (a text string followed by a colon, or a number with no colon). VBA procedures can contain any number of labels, and a GoTo statement cannot branch outside of a procedure.

The following procedure uses the VBA InputBox function to get the user's name. If the name is not Howard, the procedure branches to the WrongName label and ends. Otherwise, the procedure executes some additional code. The Exit Sub statement causes the procedure to end.

Sub GoToDemo()

UserName = InputBox("Enter Your Name:") If UserName <> "Howard" Then GoTo WrongName MsgBox ("Welcome Howard...") ' -[More code here] -

Exit Sub WrongName:

MsgBox "Sorry. Only Howard can run this." End Sub

This simple procedure works, but in general you should use the GoTo statement only when there is no other way to perform an action. In fact, the only time you really need to use a GoTo statement in VBA is for error trapping (refer to Chapter 9).

By the way, the preceding example is not intended to demonstrate a useful security technique!

0 0

Post a comment