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.
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return = 0 And Level = 0 Then GoTo NextIteration
'Go to the next iteration
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
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)
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
Source: Stackoverflow.com