Skip to next iteration in loop vba

前端 未结 4 396
灰色年华
灰色年华 2020-12-17 07:59

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
    Leve         


        
相关标签:
4条回答
  • 2020-12-17 08:16

    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)

    0 讨论(0)
  • 2020-12-17 08:17

    I use Goto

      For x= 1 to 20
    
           If something then goto continue
    
           skip this code
    
      Continue:
    
      Next x
    
    0 讨论(0)
  • 2020-12-17 08:25

    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
    
    0 讨论(0)
  • 2020-12-17 08:33
    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
    
    0 讨论(0)
提交回复
热议问题