Reputation: 307
I have in my code a For loop that contains an If Else statement. When the If statement is true, I want to exit the entire For loop. There will be no further need to loop through the rest of the range. Will "Exit For" be appropriate for this?
I was looking at the Exit statement on Microsoft's website, and according to them, Exit For continues execution with the statement immediately following the Next statement. If this is true, Exit For won't work. I want to proceed past the Next command.
I can take the time to test this using a numerical counter or something, but I'd rather get a quick answer, as I'm sure this is obvious to most people on here. Thanks!
Upvotes: 0
Views: 200
Reputation: 1400
Yes you can. Using:
Sub test()
Dim x As Integer
For x = 1 To 10
If x = 2 Then
Debug.Print "here"
Exit For
Else
Debug.Print x
End If
Next x
End Sub
I get:
1
here
And with this:
Sub test4()
Dim x As Integer
For x = 1 To 10
If x = 2 Then
Debug.Print "here"
Exit For
Else
Debug.Print x
End If
Debug.Print "testing"
Next x
End Sub
I get:
1
testing
here
And with this:
Sub test4()
Dim x As Integer
For x = 1 To 10
If x = 2 Then
Debug.Print "here"
Exit For
Debug.Print "after here"
Else
Debug.Print x
End If
Debug.Print "testing"
Next x
End Sub
you get:
1
testing
here
Upvotes: 3