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

依指定次數重複陳述式群組。

語法

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

組件

部分 描述
counter For 陳述式中的必要項目。 數值變數。 迴圈的控制變數。 如需詳細資訊,請參閱這個主題後面的計數器引數
datatype 選擇性。 counter 的資料類型。 如需詳細資訊,請參閱這個主題後面的計數器引數
start 必要。 數值運算式。 counter 的初始值。
end 必要。 數值運算式。 counter 的最終值。
step 選擇性。 數值運算式。 counter 每次透過迴圈遞增的量。
statements 選擇性。 在 ForNext 之間執行指定次數的一或多個陳述式。
Continue For 選擇性。 將控制權轉移至下一個迴圈反覆運算。
Exit For 選擇性。 將控制權轉移出 For 迴圈。
Next 必要。 終止 For 迴圈的定義。

注意

To 關鍵字可用於此陳述式,以指定計數器範圍。 您也可以在 Select...Case 陳述式和陣列宣告中使用此關鍵字。 如需陣列宣告的詳細資訊,請參閱 Dim 陳述式

簡單範例

當您想將一組陳述式重複一定次數時,請使用 For...Next 結構。

在下列範例中,index 變數的開頭值為 1,隨著迴圈的每次反覆運算遞增,在 index 的值達到 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 之後結束。 -.25Step 引數會在迴圈的每次反覆運算中將值減少 0.25。

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 

提示

當您事先不知道在迴圈中執行陳述式的次數時,While...End While 陳述式Do...Loop 陳述式相當適用於此情況。 不過,當您預期要依特定次數執行迴圈時,For...Next 迴圈則會是更好的選擇。 當您第一次進入迴圈時,可以判斷反覆運算次數。

巢狀迴圈

您可以將迴圈放在另一個迴圈中,從而巢狀 For 迴圈。 下列範例示範具有不同步驟值的巢狀 For...Next 結構。 外部迴圈會針對迴圈的每次反覆運算建立字串。 內部迴圈會針對迴圈的每次反覆運算遞減迴圈計數器變數。

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 變數。

您也可以將不同種類的控制結構彼此巢狀化。 如需詳細資訊,請參閱巢狀控制結構

結束並繼續

Exit For 陳述式會立即結束 ForNext 迴圈,並將控制權轉移至 Next 陳述式之後的陳述式。

Continue For 陳述式會立即將控制權轉移至迴圈的下一次反覆運算。 如需詳細資訊,請參閱 Continue 陳述式

以下範例將示範如何使用 Continue ForExit For 陳述式。

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

您可以在 For 中放入任意數目的 Exit For 陳述式…Next 迴圈。 在巢狀 For 中使用時…Next 迴圈,Exit For 結束最內層的迴圈,並將控制權轉移至下一個較高巢狀層級。

Exit For 通常會在評估某些情況之後使用 (例如在 If...Then...Else 結構中)。 在下列情況中,您可能會想使用 Exit For

  • 繼續逐一查看是不必要的或不可能的。 錯誤值或終止要求可能會造成這種情況。

  • Try...Catch...Finally 陳述式會攔截例外狀況。 您可以在 Finally 區塊結尾使用 Exit For

  • 您擁有無限迴圈,可用於執行大量或甚至無限次數的迴圈。 如果您偵測到該情況,則可以使用 Exit For 來逸出迴圈。 如需詳細資訊,請參閱 Do...Loop 陳述式

技術實作

For...Next 迴圈啟動時,Visual Basic 會評估 startendstep。 Visual Basic 目前僅評估這些值,然後將 start 指派給 counter。 在陳述式區塊執行之前,Visual Basic 會比較 counterend。 如果 counter 已經大於 end 值 (或如果 step 為負數則較小),For 迴圈會結束並控制傳遞至 Next 陳述式之後的陳述式。 否則,便會執行陳述式區塊。

每次 Visual Basic 遇到 Next 陳述式時,都會將 counter 遞增 step,並傳回 For 陳述式。 同樣地,其會比較 counterend,然後視結果而定,再次執行區塊或結束迴圈。 此程序會繼續執行,直到 counter 傳遞 end 或遇到 Exit For 陳述式為止。

counter 傳遞 end 之前,迴圈不會停止。 如果 counter 等於 end,則迴圈會繼續。 判斷是否執行區塊的比較是:如果 step 為正數則 counter<= end,如果 step 為負數則 counter>= end

如果您在迴圈內變更 counter 的值,程式碼可能比較難以讀取和偵錯。 變更 startendstep 的值不會影響第一次進入迴圈時所決定的反覆運算值。

如果您巢狀迴圈,而編譯器在內部層級的 Next 陳述式之前遇到外部巢狀層級的 Next 陳述式,則會發出錯誤訊號。 不過,只有在每個 Next 陳述式中指定 counter 時,編譯器才能偵測到此重疊錯誤。

步驟引數

step 值可以是正數或負數。 此參數根據下表決定迴圈處理:

步驟值 迴圈執行條件
正數或零 counter<= end
負值 counter>= end

step 的預設值為 1。

計數器引數

下表指出 counter 是否定義了範圍設定為整個 For…Next 迴圈的新區域變數。 此判斷取決於 datatype 是否存在,以及是否已定義 counter

datatype 是否存在? 是否已定義 counter 結果 (counter 是否定義了範圍設定為整個 For...Next 迴圈的新區域變數)
No Yes 否,因為早已定義 counter。 如果 counter 的範圍不屬於該程序的區域範圍,便會出現編譯時間警告。
No No 是。 從 startendstep 運算式推斷資料類型。 如需型別推斷的詳細資訊,請參閱 Option Infer 陳述式區域型別推斷
Yes Yes 是,但僅限於現有 counter 變數是在程序外部定義。 該變數會保持獨立。 如果現有 counter 變數的範圍屬於該程序的區域範圍,則會出現編譯時間警告。
No 是。

counter 的資料類型會決定反覆運算類型,且必須屬於下列其中一種類型:

  • ByteSByteUShortShortUIntegerIntegerULongLongDecimalSingleDouble

  • 您使用 Enum 陳述式宣告的列舉。

  • Object

  • 具有下列運算子的 T 類型,其中 B 是可用於 Boolean 運算式的類型。

    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 變數。 此語法可改善程式的可讀性,在您擁有巢狀 For 迴圈的情況下更是如此。 您必須指定出現在對應 For 陳述式中的變數。

startendstep 運算式可以評估為任何擴展至 counter 類型的資料類型。 如果您將使用者定義型別應用於 counter,則可能須定義 CType 轉換運算子,才能將 startendstep 的類型轉換成 counter 的類型。

範例 1

下列範例會移除所有泛型清單中的項目。 此範例顯示的不是 For Each...Next 陳述式,而是依遞減順序逐一查看的 For...Next 陳述式。 此範例使用這項技術,是因為 removeAt 方法會導致在已移除項目後面的項目具有較低的索引值。

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

範例 2

下列範例會逐一查看使用 Enum 陳述式所宣告的列舉。

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

範例 3

在下列範例中,陳述式參數會使用針對 +->=<= 運算子具有運算子多載的類別。

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

另請參閱