Käse
Käse

Reputation: 615

Skip to next iteration in loop vba

I am trying to create a simple conditional loop that will go to the next iteration if a condition is true. The code I have so far is:

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If Return = 0 And Level = 0 Then
        'Go to the next iteration
    Else
    End If
Next

I have tried GoTo NextIteration, but this comes up with the error 'Label not defined'. This probably has a very simple solution, but assistance would be much appreciated. Thanks.

Upvotes: 60

Views: 396377

Answers (5)

B H
B H

Reputation: 1876

For i = 2 To 24
  Level = Cells(i, 4)
  Return = Cells(i, 5)

  If Return = 0 And Level = 0 Then
    'Go to the next iteration
    GoTo NextIteration
  Else
  End If
  ' This is how you make a line label in VBA - Do not use keyword or
  ' integer and end it in colon
  NextIteration:
Next

Upvotes: 71

AHeyne
AHeyne

Reputation: 3475

You can use a kind of continue by using a nested Do ... Loop While False:

'This sample will output 1 and 3 only

Dim i As Integer

For i = 1 To 3: Do

    If i = 2 Then Exit Do 'Exit Do is the Continue

    Debug.Print i

Loop While False: Next i

Upvotes: 3

The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.

What you want inside your for loop follows the pattern

If (your condition) Then
    'Do something
End If

In this case, your condition is Not(Return = 0 And Level = 0), so you would use

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If (Not(Return = 0 And Level = 0)) Then
        'Do something
    End If
Next i

PS: the condition is equivalent to (Return <> 0 Or Level <> 0)

Upvotes: 6

Sam
Sam

Reputation: 97

I use Goto

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x

Upvotes: 8

Tanner
Tanner

Reputation: 22753

Just do nothing once the criteria is met, otherwise do the processing you require and the For loop will go to the next item.

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If Return = 0 And Level = 0 Then
        'Do nothing
    Else
        'Do something
    End If
Next i

Or change the clause so it only processes if the conditions are met:

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If Return <> 0 Or Level <> 0 Then
        'Do something
    End If
Next i

Upvotes: 17

Related Questions