Examples: GoTo statement

This example illustrates On Error...GoTo, On...GoTo, Resume...GoTo, and GoTo.

The user enters a value. If the value is 1, 2, or 3, the On...GoTo statement transfers control to label1, label2, or label3. If the value is another number in range for On...GoTo (the range is 0-255), control moves on the next statement. If the user enters a number that is out of range for On...GoTo or that the CInt function cannot convert to an integer, an error condition occurs, and the OnError...GoTo statement transfers control to the OutOfRange label.

Depending on the user's entry, the OneTwoThree sub displays an appropriate message. If the entry is valid, an Exit Sub statement exits the Sub. If the entry is not valid, a GoTo statement transfers control to the EnterNum label, and the user is given another chance to make a valid entry.

Sub OneTwoThree
   Dim num As Integer
   On Error GoTo OutOfRange
EnterNum:
   num% = CInt(InputBox("Enter 1, 2, or 3"))
   On num% GoTo label1, label2, label3
  ' The user did not enter 1, 2, or 3, but a run-time error
  ' did not occur (the user entered a number in the 
  ' range 0-255).
   MessageBox "You did not enter a correct value! Try again!"
   GoTo EnterNum
label1:
   MessageBox "You entered 1."
   Exit Sub
label2:
   MessageBox "You entered 2."
   Exit Sub
label3:
   MessageBox "You entered 3."
   Exit Sub
   ' An error condition has occurred.
OutOfRange:
   MessageBox "The value you entered is negative, " _
      & "greater than 255, or is not a number. Try again!"
   GoTo EnterNum   
End Sub
OneTwoThree   ' Call the OneTwoThree sub.