Excel VBA - exit for loop

ExcelVbaFor Loop

Excel Problem Overview


I would like to exit my for loop when a condition inside is met. How could I exit my for loop when the if condition has been met? I think some kind of exit at the end of my if statement, but don't know how that would work.

Dim i As Long
For i = 1 To 50
    Range("B" & i).Select
    If Range("B" & i).Value = "Artikel" Then
        Dim temp As Long
        temp = i
    End If
Next i
Range("A1:Z" & temp - 1).EntireRow.Delete Shift:=xlToLeft

Excel Solutions


Solution 1 - Excel

To exit your loop early you can use Exit For

If [condition] Then Exit For

Solution 2 - Excel

Another way to exit a For loop early is by changing the loop counter:

For i = 1 To 10
    If i = 5 Then i = 10
Next i

Debug.Print i   '11

For i = 1 To 10
    If i = 5 Then Exit For
Next i

Debug.Print i   '5

Solution 3 - Excel

The first answer given with the following is indeed i.m.o. best practice:

if i = 0 then exit for

However, this is also an option:

Sub some()

Count = 0
End_ = ThisWorkbook.Sheets(1).Range("B1047854").End(xlUp).Row

While Count < End_ And Not ThisWorkbook.Sheets(1).Range("B" & Count).Value = "Artikel"
    Count = Count + 1
    If ThisWorkbook.Sheets(1).Range("B" & Count).Value = "Artikel" Then
        ThisWorkbook.Sheets(1).Range("A1:Z" & Count - 1).EntireRow.Delete Shift:=xlToLeft
    End If
Wend

End Sub

Solution 4 - Excel

if condition (inside your while - loop) then goto (some marker outside the loop)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCustomXView Question on Stackoverflow
Solution 1 - ExcelDanView Answer on Stackoverflow
Solution 2 - Excelpaul bicaView Answer on Stackoverflow
Solution 3 - Excelko_00View Answer on Stackoverflow
Solution 4 - Exceluser18858896View Answer on Stackoverflow