Chas
Chas

Reputation: 107

VBA If Else within For Next Loop

I need a VBA If Else statement within a For Next loop

I have tried various arrangements of the statements, but they all error out.

Sub TestForIfElse()
   Dim Counter As Integer
   Dim i As Integer

   For i = 1 To 5

   Counter = i

   If Counter > 3 Then

        Exit For

    Else

    Next i   'ERROR NEXT WITHOUT FOR
End Sub

Run loop until test is met.

If Test not met, keep going

If test met, exit loop. Thanks for your help.

Upvotes: 0

Views: 1312

Answers (1)

Mikku
Mikku

Reputation: 6654

This will work:

Sub TestForIfElse()

   Dim Counter As Integer
   Dim i As Integer

   For i = 1 To 5

       Counter = i

       If Counter > 3 Then

            Exit For

       End If

   Next i

End Sub

Upvotes: 2

Related Questions