Exit For

This statement provides a way to exit the loop early.
It can only be used inside a For - Next or a For Each - Next loop.
This transfers control to the statement that immediately follows the Next statement.

Exit For 

For - Next

This loop will exit at the start of the third loop.

Public Sub ExitFor1() 
Dim icount As Integer
   For icount = 1 To 5
      If (icount = 3) Then
         Exit For
      End If
   Next icount
   Debug.Print icount '3
End Sub

For - Each

This loop will exit after it finds the item "tw".

Public Sub ExitFor2() 
Dim arValues As Variant
Dim oItem As Variant
   arValues = Array("on", "tw", "th", "fo")
   For Each oItem In arValues
      If (oItem = "tw") Then
         Exit For
      End If
   Next oItem
   Debug.Print oItem 'tw
End Sub

Nested Loops

This statement transfers control to the statement that immediately follows the Next statement.
If a loop is nested, the control is passed only one level up.

Public Sub ExitFor3() 
Dim iouter As Integer
Dim inner As Integer
   For iouter = 1 To 5
      For inner = 2 To 4
         Debug.Print "inner - " & inner
         If (inner = 3) Then
            Exit For 'only exits the inner loop
         End If
      Next inner
      Debug.Print "outer - " & iouter
   Next iouter
End Sub

Important

You can use one or more Exit For statements inside the same loop.


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext