[Solved] Conditional Next of a loop

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Post Reply
gurkand
Posts: 29
Joined: Wed Feb 28, 2018 10:27 am

[Solved] Conditional Next of a loop

Post 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,
Last edited by RoryOF on Wed Feb 28, 2018 3:55 pm, edited 2 times in total.
Reason: Added green tick [RoryOF, Moderator]
LibreOffice 6.3
User avatar
RoryOF
Moderator
Posts: 34611
Joined: Sat Jan 31, 2009 9:30 pm
Location: Ireland

Re: Conditional Next of a loop

Post by RoryOF »

Invert your test.
FOR i = 1 TO 10
IF I<>5 THEN
do something
ELSE
do something_else
END IF
NEXT I
Apache OpenOffice 4.1.15 on Xubuntu 22.04.4 LTS
User avatar
Lupp
Volunteer
Posts: 3548
Joined: Sat May 31, 2014 7:05 pm
Location: München, Germany

Re: [Solved] Conditional Next of a loop

Post 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

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.
On Windows 10: LibreOffice 24.2 (new numbering) and older versions, PortableOpenOffice 4.1.7 and older, StarOffice 5.2
---
Lupp from München
Post Reply