0

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.

2
  • 3
    Replace Else with End If. Commented Jun 21, 2019 at 3:25
  • 1
    You need to include an End If if you want to use If Else. So you would use If... Else... End If Commented Jun 21, 2019 at 7:24

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Worked beautifully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.