[Solved] Conditional Next of a loop

Creating a macro - Writing a Script - Using the API

[Solved] Conditional Next of a loop

Postby gurkand » Wed Feb 28, 2018 10:37 am

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.

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
Posts: 29
Joined: Wed Feb 28, 2018 10:27 am

Re: Conditional Next of a loop

Postby RoryOF » Wed Feb 28, 2018 3:20 pm

Invert your test.
FOR i = 1 TO 10
do something
do something_else
Apache OpenOffice 4.1.7 on Xubuntu 18.04.4 (mostly 64 bit version) and very infrequently on Win2K/XP
User avatar
Posts: 31239
Joined: Sat Jan 31, 2009 9:30 pm
Location: Ireland

Re: [Solved] Conditional Next of a loop

Postby Lupp » Wed Feb 28, 2018 6:26 pm

'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
    If testThis(z) Then Goto next_i
  End If
Next i

Generally I would prefer complete alternatives.
On Windows 10: LibreOffice 7.0 and older versions, PortableOpenOffice 4.1.7 and older, StarOffice 5.2
Lupp from München
User avatar
Posts: 2897
Joined: Sat May 31, 2014 7:05 pm
Location: München, Germany

Return to Macros and UNO API

Who is online

Users browsing this forum: No registered users and 3 guests