The GoTo Statement

A GoTo statement offers the most straightforward means for changing a program's flow. The GoTo statement simply transfers program control to a new statement, which is preceded by a label.

Your VBA routines can contain as many labels as you like. A label is just a text string followed by a colon. (See Chapter 7 for more label information.)

The following procedure shows how a GoTo statement works:

Sub GoToDemo()

UserName = InputBox("

Enter Your Name: ")

If UserName <> "Bill

Gates" Then GoTo WrongName

MsgBox ("Welcome Bill


' ...[More code here] .

Exit Sub


MsgBox "Sorry. Only B

ill Gates can run this."

End Sub

The procedure uses the InputBox function to get the user's name. If the user enters a name other than Bill Gates, the program flow jumps to the WrongName label, displays an apologetic message, and the procedure ends. On the other hand, if Mr. Gates signs on, the procedure displays a welcome message and then executes some additional code (not shown in the example). The Exit Sub statement ends the procedure before the second MsgBox function has a chance to work.

This simple routine works, but VBA provides several better (and more structured) alternatives than GoTo. In general, you should use GoTo only when you have no other way to perform an action. In practice, the only time you really need to use a GoTo statement is for trapping errors. (I cover this in Chapter 12.)

^jUNG/ Many hard-core programming types have a deep-seated hatred for GoTo statements because using them tends to result in difficult-to-read "spaghetti code." Therefore, you should avoid this subject when talking with other programmers.

Was this article helpful?

0 0

Post a comment