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, but 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 it's not an example of good programming. 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 handling (refer to Chapter 9).

Finally, it goes without saying that the preceding example is not intended to demonstrate an effective security technique!

0 0

Post a comment