Exiting a For...Next Loop Early : Exit « Language Basics « VBA / Excel / Access / Word






Exiting a For...Next Loop Early

 
Sub ExitForExample()
    Dim nLastRow As Integer
    Dim nColumn As Integer
    Dim nRow As Integer
    Dim ws As Worksheet

    Set ws = ThisWorkbook.Worksheets(1)
    nLastRow = 15
    nColumn = 1

    For nRow = 1 To nLastRow
        If ws.Cells(nRow, nColumn).Address = "$A$7" Then
            Debug.Print "Found cell. Exiting for loop."
            Exit For
        Else
            Debug.Print ws.Cells(nRow, nColumn).Address
        End If
    Next

    Set ws = Nothing
End Sub

 








Related examples in the same category

1.Using an Exit Do Statement
2.A Generic Procedure Skeleton with Basic Error Handling