Continue For loop

前端 未结 8 1580
面向向阳花
面向向阳花 2020-11-27 05:29

I have the following code

For x = LBound(arr) To UBound(arr)

    sname = arr(x)  
    If instr(sname, \"Configuration item\") Then  
        \'**(here i wa         


        
相关标签:
8条回答
  • 2020-11-27 06:06

    I sometimes do a double do loop:

    Do
    
        Do
    
            If I_Don't_Want_to_Finish_This_Loop Then Exit Do
    
            Exit Do
    
        Loop
    
    Loop Until Done
    

    This avoids having "goto spaghetti"

    0 讨论(0)
  • 2020-11-27 06:13

    A few years late, but here is another alternative.

    For x = LBound(arr) To UBound(arr)
        sname = arr(x)  
        If InStr(sname, "Configuration item") Then  
            'Do nothing here, which automatically go to the next iteration
        Else
            'Code to perform the required action
        End If
    Next x
    
    0 讨论(0)
  • 2020-11-27 06:15

    You're thinking of a continue statement like Java's or Python's, but VBA has no such native statement, and you can't use VBA's Next like that.

    You could achieve something like what you're trying to do using a GoTo statement instead, but really, GoTo should be reserved for cases where the alternatives are contrived and impractical.

    In your case with a single "continue" condition, there's a really simple, clean, and readable alternative:

        If Not InStr(sname, "Configuration item") Then
            '// other code to copy paste and do various stuff
        End If
    
    0 讨论(0)
  • 2020-11-27 06:17

    A lot of years after... I like this one:

    For x = LBound(arr) To UBound(arr): Do
    
        sname = arr(x)  
        If instr(sname, "Configuration item") Then Exit Do 
    
        '// other code to copy past and do various stuff
    
    Loop While False: Next x
    
    0 讨论(0)
  • 2020-11-27 06:18

    For the case you do not use "DO": this is my solution for a FOR EACH with nested If conditional statements:

    For Each line In lines
        If <1st condition> Then
            <code if 1st condition>
            If <2nd condition> Then
                If <3rd condition> Then
                    GoTo ContinueForEach
                Else
                    <code else 3rd condition>
                End If
            Else
                <code else 2nd condition>
            End If
        Else
            <code else 1st condition>
        End If
    ContinueForEach:
    Next
    
    0 讨论(0)
  • 2020-11-27 06:19
    For i=1 To 10
        Do 
            'Do everything in here and
    
            If I_Dont_Want_Finish_This_Loop Then
                Exit Do
            End If 
    
            'Of course, if I do want to finish it,
            'I put more stuff here, and then...
    
        Loop While False 'quit after one loop
    Next i
    
    0 讨论(0)
提交回复
热议问题