-1

How to stop execution of current iteration of for loop statement ? Exit ends execution of whole loop, have I realy use goto ?

Qbik
  • 5,885
  • 14
  • 62
  • 93
  • 2
    This is a poorly written question. Mainly because you haven't explained if you want to skip ONE iteration of the loop or Exit the loop completely. Under what conditions would you like to skip/exit? What have you tried so far other than `Exit`? – Chrismas007 Mar 03 '15 at 16:03
  • possible duplicate of [VBA - how to conditionally skip a for loop iteration](http://stackoverflow.com/questions/8680640/vba-how-to-conditionally-skip-a-for-loop-iteration) – Mathieu Guindon Mar 03 '15 at 16:52

1 Answers1

3

You'll usually want to skip an iteration when a given condition is met - you have 2 options in VBA:

  1. Wrap the loop body in an If block:

        For i = 1 to 100
            If SomeCondition Then
                ' interesting iterations
            End If
        Next
    
  2. Use GoTo to skip an iteration (and reduce nesting):

        For i = 1 to 100
            If Not SomeCondition Then GoTo Skip
    
            ' interesting iterations
    
    Skip:
        Next
    

Yes, GoTo is bad. But this is an old language, and GoTo does have legitimate uses - that's one of them. If you keep your code clean and extract the loop body into its own procedure, there shouldn't be any readability issues with using it.

Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235