在 [...]GoSub、...]GoTo 陳述式On...GoSub, On...GoTo statements

分支至數個選項的其中一個指定的行,根據運算式的值。Branch to one of several specified lines, depending on the value of an expression.

語法Syntax

運算式GoSubdestinationlistOn expression GoSub destinationlist
運算式移至destinationlistOn expression GoTo destinationlist


...]GoSub上...]GoTo陳述式語法具有以下幾個部分:The On...GoSub and On...GoTo statement syntax has these parts:

部分Part 描述Description
運算式expression 必要。Required. 任何數值運算式,評估為介於 0 到 255 之間,(含) 之間的整數。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.
destinationlistdestinationlist 必要項目。Required. 行號行標籤以逗號分隔的清單。List of line numbers or line labels separated by commas.

註解Remarks

_運算式_的值會決定哪一行分支到_destinationlist_中。The value of expression determines which line is branched to in destinationlist. 如果_運算式_的值小於 1 或大於清單中的項目數,則會發生下列其中一個下列結果:If the value of expression is less than 1 or greater than the number of items in the list, one of the following results occurs:

如果_運算式_為If expression is ThenThen
等於 0Equal to 0 控制項減到陳述式下列上...]GoSub上...]GoToControl drops to the statement following On...GoSub or On...GoTo.
大於清單中的項目數Greater than number of items in list 控制項減到之後的陳述式上...]GoSub上...]GoToControl drops to the statement following On...GoSub or On...GoTo.
NegativeNegative 會發生錯誤。An error occurs.
大於 255Greater than 255 會發生錯誤。An error occurs.

您可以混合行號與相同的清單中的行標籤。You can mix line numbers and line labels in the same list. 您可以使用許多行標籤和行號依您喜好與上...]GoSub上...]GoToYou can use as many line labels and line numbers as you like with On...GoSub and On...GoTo. 不過,如果您在單一行上使用更多的標籤或比調整的數字,您必須使用行接續字元接續邏輯行到下一個實體行。However, if you use more labels or numbers than fit on a single line, you must use the line-continuation character to continue the logical line onto the next physical line.

提示

Select Case提供更結構化且具有彈性的方式,來執行多個分支。Select Case provides a more structured and flexible way to perform multiple branching.

範例Example

本範例會在使用 ...]GoSub上...]GoTo分別分支到副程式及行標籤的陳述式。This example uses the On...GoSub and On...GoTo statements to branch to subroutines and line labels, respectively.

Sub OnGosubGotoDemo() 
Dim Number, MyString 
 Number = 2 ' Initialize variable. 
 ' Branch to Sub2. 
 On Number GoSub Sub1, Sub2 ' Execution resumes here after 
 ' On...GoSub. 
 On Number GoTo Line1, Line2 ' Branch to Line2. 
 ' Execution does not resume here after On...GoTo. 
 Exit Sub 
Sub1: 
 MyString = "In Sub1" : Return 
Sub2: 
 MyString = "In Sub2" : Return 
Line1: 
 MyString = "In Line1" 
Line2: 
 MyString = "In Line2" 
End Sub

另請參閱See also

支援和意見反應Support and feedback

有關於 Office VBA 或這份文件的問題或意見反應嗎?Have questions or feedback about Office VBA or this documentation? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.