Page 1 of 1

[Solved] Conditional Next of a loop

PostPosted: Wed Feb 28, 2018 10:37 am
by gurkand
Hi All,

For I = 1 To 10
If I = 5 Then
Exit For
End If
' ... Inner part of loop
Next I

This is easy.

But, I do not want to Exit the For, instead I want to skip the rest of the inner part of the loop and go for the Next I. So I want to do something like:

For I = 1 To 10
If <condition> Then
Next I <----- This is the bit I want...
End If
' ... Inner part of loop
Next I

But it does not work when I code this.

Without coding any other costly loops, checks, or moving " ' ... Inner part of loop " into the Then/Else part of the If (which is decreasing the readability)... is there a way to do this?

Thanks in advance.

Regards,

Re: Conditional Next of a loop

PostPosted: Wed Feb 28, 2018 3:20 pm
by RoryOF
Invert your test.
FOR i = 1 TO 10
IF I<>5 THEN
do something
ELSE
do something_else
END IF
NEXT I

Re: [Solved] Conditional Next of a loop

PostPosted: Wed Feb 28, 2018 6:26 pm
by Lupp
'Next i' is not allowed to occur more often than once for the same 'For i' loop and the For-Next construct cannot be interlaced with a different control structure.
If there is an urgent reason not to do it the way Rory suggested you may resort to the old Goto-statement like in
Code: Select all   Expand viewCollapse view
For i = 1 To 5
  If testSomething(a,b) Then
    DoThis(C,D)
    If testThis(z) Then Goto next_i
    continueWith(y)
  End If
  tryThis(e,f)
next_i:
Next i

Generally I would prefer complete alternatives.