For...Next 陳述式 (Visual Basic)For...Next Statement (Visual Basic)

重複指定次數的語句群組。Repeats a group of statements a specified number of times.

語法Syntax

For counter [ As datatype ] = start To end [ Step step ]
    [ statements ]
    [ Continue For ]
    [ statements ]
    [ Exit For ]
    [ statements ]
Next [ counter ]

組件Parts

組件Part 描述Description
counter For 語句中是必要的。Required in the For statement. 數值變數。Numeric variable. 迴圈的控制變數。The control variable for the loop. 如需詳細資訊,請參閱本主題稍後的計數器引數For more information, see Counter Argument later in this topic.
datatype 選擇項。Optional. @No__t_0 的資料類型。Data type of counter. 如需詳細資訊,請參閱本主題稍後的計數器引數For more information, see Counter Argument later in this topic.
start 必要項。Required. 數值運算式。Numeric expression. counter 的初始值。The initial value of counter.
end 必要項。Required. 數值運算式。Numeric expression. @No__t_0 的最終值。The final value of counter.
step 選擇項。Optional. 數值運算式。Numeric expression. 每次執行迴圈時,counter 的遞增量。The amount by which counter is incremented each time through the loop.
statements 選擇項。Optional. @No__t_0 和 Next 之間的一個或多個語句執行指定的次數。One or more statements between For and Next that run the specified number of times.
Continue For 選擇項。Optional. 將控制權轉移至下一個迴圈反復專案。Transfers control to the next loop iteration.
Exit For 選擇項。Optional. 將控制權轉移 For 迴圈。Transfers control out of the For loop.
Next 必要項。Required. 結束 For 迴圈的定義。Terminates the definition of the For loop.

注意

這個語句中會使用 To 關鍵字來指定計數器的範圍。The To keyword is used in this statement to specify the range for the counter. 您也可以在 [選取 ...] 中使用此關鍵字Case 語句和陣列宣告。You can also use this keyword in the Select...Case Statement and in array declarations. 如需陣列宣告的詳細資訊,請參閱Dim 語句For more information about array declarations, see Dim Statement.

簡單範例Simple Examples

您使用 For .。。當您想要以設定的次數重複一組語句時,Next 結構。You use a For...Next structure when you want to repeat a set of statements a set number of times.

在下列範例中,index 變數的開頭為1的值,而且會隨著迴圈的每個反復專案而遞增,並在 index 的值到達5之後結束。In the following example, the index variable starts with a value of 1 and is incremented with each iteration of the loop, ending after the value of index reaches 5.

For index As Integer = 1 To 5
    Debug.Write(index.ToString & " ")
Next
Debug.WriteLine("")
' Output: 1 2 3 4 5

在下列範例中,number 變數會從2開始,並在迴圈的每次反覆運算時減少0.25,並在 number 的值到達0之後結束。In the following example, the number variable starts at 2 and is reduced by 0.25 on each iteration of the loop, ending after the value of number reaches 0. @No__t_1 的 Step 引數會在迴圈的每個反覆運算上減少0.25 的值。The Step argument of -.25 reduces the value by 0.25 on each iteration of the loop.

For number As Double = 2 To 0 Step -0.25
    Debug.Write(number.ToString & " ")
Next
Debug.WriteLine("")
' Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0 

提示

A While .。。End While 語句Do .。。當您事先不知道要在迴圈中執行語句的次數時,Loop 語句的運作效果很好。A While...End While Statement or Do...Loop Statement works well when you don't know in advance how many times to run the statements in the loop. 不過,當您預期會執行特定次數的迴圈時,For .。。Next 迴圈是較佳的選擇。However, when you expect to run the loop a specific number of times, a For...Next loop is a better choice. 您會在第一次進入迴圈時判斷反覆運算次數。You determine the number of iterations when you first enter the loop.

嵌套迴圈Nesting Loops

您可以藉由將一個迴圈放在另一個迴圈中,來將 For 迴圈。You can nest For loops by putting one loop within another. 下列範例示範的是 nested For .。。具有不同步驟值的 Next 結構。The following example demonstrates nested For...Next structures that have different step values. 外部迴圈會為迴圈的每個反覆運算建立一個字串。The outer loop creates a string for every iteration of the loop. 內部迴圈會針對迴圈的每個反覆運算遞減迴圈計數器變數。The inner loop decrements a loop counter variable for every iteration of the loop.

For indexA = 1 To 3
    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Append to the StringBuilder every third number
    ' from 20 to 1 descending.
    For indexB = 20 To 1 Step -3
        sb.Append(indexB.ToString)
        sb.Append(" ")
    Next indexB

    ' Display the line.
    Debug.WriteLine(sb.ToString)
Next indexA
' Output:
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2

當嵌套迴圈時,每個迴圈都必須有唯一的 counter 變數。When nesting loops, each loop must have a unique counter variable.

您也可以將不同類型的控制結構分別放在其中。You can also nest different kinds control structures within each other. 如需詳細資訊,請參閱嵌套控制項結構For more information, see Nested Control Structures.

結束並繼續進行Exit For and Continue For

@No__t_0 語句會立即離開 For ... NextThe Exit For statement immediately exits the ForNext 迴圈,並將控制權轉移至 Next 語句後面的語句。loop and transfers control to the statement that follows the Next statement.

@No__t_0 語句會立即將控制權轉移到迴圈的下一個反復專案。The Continue For statement transfers control immediately to the next iteration of the loop. 如需詳細資訊,請參閱Continue 語句For more information, see Continue Statement.

下列範例說明如何使用 Continue ForExit For 語句。The following example illustrates the use of the Continue For and Exit For statements.

For index As Integer = 1 To 100000
    ' If index is between 5 and 7, continue
    ' with the next iteration.
    If index >= 5 AndAlso index <= 8 Then
        Continue For
    End If

    ' Display the index.
    Debug.Write(index.ToString & " ")

    ' If index is 10, exit the loop.
    If index = 10 Then
        Exit For
    End If
Next
Debug.WriteLine("")
' Output: 1 2 3 4 9 10

您可以將任意數目的 Exit For 語句放在 For ... NextYou can put any number of Exit For statements in a ForNext 進入.loop. 在 nested For 中使用時 ... NextWhen used within nested ForNext 迴圈,Exit For 會結束最內層的迴圈,並將控制權轉移至下一個較高層級的嵌套。loops, Exit For exits the innermost loop and transfers control to the next higher level of nesting.

在您評估某個條件(例如,在 If ... Then ... Else 結構)之後,通常會使用 Exit ForExit For is often used after you evaluate some condition (for example, in an If...Then...Else structure). 在下列情況中,您可能會想要使用 Exit ForYou might want to use Exit For for the following conditions:

  • 繼續進行反覆運算是不必要或不可能的。Continuing to iterate is unnecessary or impossible. 錯誤值或終止要求可能會建立此條件。An erroneous value or a termination request might create this condition.

  • @No__t_0 .。。Catch .。。Finally 語句會攔截例外狀況。A Try...Catch...Finally statement catches an exception. 您可以使用 Finally 區塊結尾處的 Exit ForYou might use Exit For at the end of the Finally block.

  • 您有一個無止盡的迴圈,這是一種迴圈,可能會執行很長或甚至無限次數。You have an endless loop, which is a loop that could run a large or even infinite number of times. 如果您偵測到這種情況,您可以使用 Exit For 來對迴圈進行 escape。If you detect such a condition, you can use Exit For to escape the loop. 如需詳細資訊,請參閱Do .。。Loop 語句For more information, see Do...Loop Statement.

技術實作Technical Implementation

For .。。Next 迴圈開始時,Visual Basic 會評估 startendstepWhen a For...Next loop starts, Visual Basic evaluates start, end, and step. Visual Basic 只會在這段時間評估這些值,然後將 start 指派給 counterVisual Basic evaluates these values only at this time and then assigns start to counter. 在執行語句區塊之前,Visual Basic 會比較 counterendBefore the statement block runs, Visual Basic compares counter to end. 如果 counter 已經大於 end 值(如果 step 是負數,則較小),For 迴圈就會結束,並將控制權傳遞至緊接在 Next 語句之後的語句。If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement that follows the Next statement. 否則,會執行語句區塊。Otherwise, the statement block runs.

每次 Visual Basic 遇到 Next 語句時,它會以 step 遞增 counter,並返回 For 語句。Each time Visual Basic encounters the Next statement, it increments counter by step and returns to the For statement. 同樣地,它會比較 counterend,然後根據結果,執行區塊或結束迴圈。Again it compares counter to end, and again it either runs the block or exits the loop, depending on the result. 此程式會繼續進行,直到 counter 通過 end 或遇到 Exit For 語句為止。This process continues until counter passes end or an Exit For statement is encountered.

直到 counter 傳遞 end 後,迴圈才會停止。The loop doesn't stop until counter has passed end. 如果 counter 等於 end,迴圈就會繼續進行。If counter is equal to end, the loop continues. 如果 step 為正數,則決定是否要執行區塊的比較 counter <= end 如果 counter 為負數,則 >= end stepThe comparison that determines whether to run the block is counter <= end if step is positive and counter >= end if step is negative.

如果您在迴圈內變更 counter 的值,您的程式碼可能會更容易讀取和 debug。If you change the value of counter while inside a loop, your code might be more difficult to read and debug. 變更 startendstep 的值,並不會影響第一次進入迴圈時所決定的反復專案值。Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.

如果您嵌套迴圈,編譯器在內部層級的 Next 語句之前遇到外部嵌套層級的 Next 語句時,會發出錯誤信號。If you nest loops, the compiler signals an error if it encounters the Next statement of an outer nesting level before the Next statement of an inner level. 不過,只有當您在每個 Next 語句中指定 counter 時,編譯器才能夠偵測到這個重迭的錯誤。However, the compiler can detect this overlapping error only if you specify counter in every Next statement.

Step 引數Step Argument

@No__t_0 的值可以是正數或負數。The value of step can be either positive or negative. 這個參數會根據下表來決定迴圈處理:This parameter determines loop processing according to the following table:

步驟值Step value 迴圈執行(如果Loop executes if
正數或零Positive or zero counter <= end
Negative counter >= end

@No__t_0 的預設值為1。The default value of step is 1.

Counter 引數Counter Argument

下表指出 counter 是否定義範圍設定為整個 For…Next 迴圈的新區域變數。The following table indicates whether counter defines a new local variable that’s scoped to the entire For…Next loop. 這項決定取決於是否存在 datatype,以及 counter 是否已定義。This determination depends on whether datatype is present and whether counter is already defined.

@No__t_0 存在嗎?Is datatype present? @No__t_0 已經定義了嗎?Is counter already defined? Result (counter 是否定義範圍設定為整個 For...Next 迴圈的新區域變數)Result (whether counter defines a new local variable that’s scoped to the entire For...Next loop)
No [是]Yes 否,因為已定義 counterNo, because counter is already defined. 如果 counter 的範圍不是程式的本機,就會發生編譯時期警告。If the scope of counter isn't local to the procedure, a compile-time warning occurs.
No No 可以。Yes. 資料類型是從 [start]、[end] 和 [step] 運算式推斷而來。The data type is inferred from the start, end, and step expressions. 如需型別推斷的詳細資訊,請參閱Option 推斷語句區欄位型別推斷For information about type inference, see Option Infer Statement and Local Type Inference.
[是]Yes [是]Yes 是,但只有在程式之外定義了現有的 counter 變數時。Yes, but only if the existing counter variable is defined outside the procedure. 該變數會保持不變。That variable remains separate. 如果現有 counter 變數的範圍是程式的本機,就會發生編譯時期錯誤。If the scope of the existing counter variable is local to the procedure, a compile-time error occurs.
[是]Yes No 可以。Yes.

@No__t_0 的資料類型會決定反復專案的類型,必須是下列其中一種類型:The data type of counter determines the type of the iteration, which must be one of the following types:

  • @No__t_0、`SByte`、`UShort`、`Short`、`UInteger`、`Integer`、`ULong`、`Long`、`Decimal`、`Single` 或 0。A Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.

  • 使用Enum 語句宣告的列舉。An enumeration that you declare by using an Enum Statement.

  • ObjectAn Object.

  • 具有下列運算子的類型 T,其中 B 是可用於 Boolean 運算式的類型。A type T that has the following operators, where B is a type that can be used in a Boolean expression.

    Public Shared Operator >= (op1 As T, op2 As T) As B

    Public Shared Operator <= (op1 As T, op2 As T) As B

    Public Shared Operator - (op1 As T, op2 As T) As T

    Public Shared Operator + (op1 As T, op2 As T) As T

您可以選擇性地在 Next 語句中指定 counter 變數。You can optionally specify the counter variable in the Next statement. 此語法可改善程式的可讀性,特別是如果您有嵌套的 For 迴圈。This syntax improves the readability of your program, especially if you have nested For loops. 您必須指定出現在對應的 For 語句中的變數。You must specify the variable that appears in the corresponding For statement.

@No__t_0、`end` 和 step 運算式可以評估為任何擴大至 counter 類型的資料類型。The start, end, and step expressions can evaluate to any data type that widens to the type of counter. 如果您使用 counter 的使用者定義型別,您可能必須定義 CType 轉換運算子,以將 startendstep 的類型轉換成 counter 的類型。If you use a user-defined type for counter, you might have to define the CType conversion operator to convert the types of start, end, or step to the type of counter.

範例Example

下列範例會從泛型清單中移除所有元素。The following example removes all elements from a generic list. 而不是針對每個 .。。下一個語句,此範例會顯示 For .。。以遞減順序逐一查看的 Next 語句。Instead of a For Each...Next Statement, the example shows a For...Next statement that iterates in descending order. 此範例會使用這項技術,因為 removeAt 方法會使已移除專案之後的元素具有較低的索引值。The example uses this technique because the removeAt method causes elements after the removed element to have a lower index value.

Dim lst As New List(Of Integer) From {10, 20, 30, 40}

For index As Integer = lst.Count - 1 To 0 Step -1
    lst.RemoveAt(index)
Next

Debug.WriteLine(lst.Count.ToString)
' Output: 0

範例Example

下列範例會逐一查看使用Enum 語句宣告的列舉。The following example iterates through an enumeration that's declared by using an Enum Statement.

Public Enum Mammals
    Buffalo
    Gazelle
    Mongoose
    Rhinoceros
    Whale
End Enum


Public Sub ListSomeMammals()
    For mammal As Mammals = Mammals.Gazelle To Mammals.Rhinoceros
        Debug.Write(mammal.ToString & " ")
    Next
    Debug.WriteLine("")
    ' Output: Gazelle Mongoose Rhinoceros
End Sub

範例Example

在下列範例中,語句參數使用的類別具有 +->=<= 運算子的運算子多載。In the following example, the statement parameters use a class that has operator overloads for the +, -, >=, and <= operators.

Private Class Distance
    Public Property Number() As Double

    Public Sub New(ByVal number As Double)
        Me.Number = number
    End Sub

    ' Define operator overloads to support For...Next statements.
    Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As Distance
        Return New Distance(op1.Number + op2.Number)
    End Operator

    Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As Distance
        Return New Distance(op1.Number - op2.Number)
    End Operator

    Public Shared Operator >=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean
        Return (op1.Number >= op2.Number)
    End Operator

    Public Shared Operator <=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean
        Return (op1.Number <= op2.Number)
    End Operator
End Class


Public Sub ListDistances()
    Dim distFrom As New Distance(10)
    Dim distTo As New Distance(25)
    Dim distStep As New Distance(4)

    For dist As Distance = distFrom To distTo Step distStep
        Debug.Write(dist.Number.ToString & " ")
    Next
    Debug.WriteLine("")

    ' Output: 10 14 18 22 
End Sub

請參閱See also