On...GoTo Statement

Branch to one of several specified lines, depending on the value of an expression.

Syntax

On expression GoTo destinationlist

The On...GoTo statement syntax has these parts:

Part Description
expression Required. Any numeric expression that evaluates to a whole number between 0 and 255, inclusive. If expression is any number other than a whole number, it is rounded before it is evaluated.
destinationlist Required. List of line numbers or line labels separated by commas.

Remarks

The value of expression determines which line is branched to in destinationlist. If the value of expression is less than 1 or greater than the number of items in the list or greater than 255 then control drops to the statement following On...GoTo.

You can mix line numbers and line labels in the same list.

    Tip: Select Case provides a more structured and flexible way to perform multiple branching.

Example

Sub OnGoToDemo()
Dim Number, MyString

MyString = "Nothing"
Number = InputBox("Enter branch number:") ' Initialize variable.
' Branch to Line<Number>.
On Number GoTo Line1, Line2
TraceHandle:
Trace MyString

Exit Sub
Line1:
MyString = "In Line1" : GoTo TraceHandle
Line2:
MyString = "In Line2" : GoTo TraceHandle
End Sub

 

See Also

GoSub...Return Statement, GoTo Statement, On...GoSub Statement, Select Case Statement