|< Day Day Up >|
There's one final flow-of-control statement that you should know about: the GoTo statement. GoTo produces an unconditional change in the flow of your program. Here's an example of the GoTo statement in action:
Sub CalculateBill(curRate As Currency, intHours As Integer) ' Calculate the bill for this line item If intHours > 100 Then GoTo ExitHere End If Debug.Print curRate * intHours ExitHere: End Sub
In this code, ExitHere is an example of a label. A label is not executed by VBA. Rather, it is a bookmark within the code that VBA can refer to by name.
The GoTo statement transfers the program flow to the specified label. So in this particular procedure, the effect is to exit from the entire procedure if the intHours variable has a value of more than 100.
The GoTo statement has been a subject of debate for many years. Most professional developers agree that using GoTo can make your code harder to read and understand, because you have to jump around to follow the code when you're reading it. And in most cases, you can rewrite code to avoid the GoTo statement. For example, here's another version of the CalculateBill procedure:
Sub CalculateBill(curRate As Currency, intHours As Integer) ' Calculate the bill for this line item If intHours <= 100 Then Debug.Print curRate * intHours End If End Sub
This version has exactly the same effect as the first version, but it does not use the GoTo statement.
On the whole, I agree with those who feel that the GoTo statement should be avoided. You might occasionally find that using GoTo makes your code seem more clear, and in those cases, there's nothing wrong with using GoTo. For example, if there are many places within a complex procedure where you want to execute cleanup code and then terminate the procedure, you might use GoTo statements to avoid having to repeat the cleanup code. But don't leap to use GoTo as your first tool in all cases.
The GoTo statement is necessary as a part of the On Error GoTo error-trapping statement, and you shouldnt avoid using that statement just because it includes a GoTo. See "Using On Error GoTo," on p. 53.
|< Day Day Up >|