Jose M.
Jose M.

Reputation: 2350

For Loop, how to skip iterations

I am trying to figure out how to skip iterations on a For loop. I did some research and found that I could use Continue For, but that does not solve my issue. Here an example of what I want to do:

For i As Long = 1 to 7 Step 1
    If (i= 2, 5 and 7) Then
        'perform this action
    Else
        'perform other action.
    End If
Next i

I worked out the following, but unfortunately it works for the <= 2 and the Else part of my loop and for the 5 and 7, performs the same action as what I asked to do on the Else part.

For i As Long = 1 To 7 Step 1
    If (i <= 2 AndAlso 5 AndAlso 7) Then
        strRange = ("A:D")
    Else
        strRange = ("A:A")
    End If

    xlRefSheets = ClientSheets(i)

    With xlRefSheets
        .Cells.EntireColumn.AutoFit()
        .Range(strRange).EntireColumn.Hidden = True
    End With
Next i

Upvotes: 1

Views: 652

Answers (1)

Ryan
Ryan

Reputation: 28247

How about restating the if clause to

If (i <= 2) or (i = 5) or ( i =7)  Then
   ...

So your code becomes:

  For i As Long = 1 To 7 Step 1
    If (i <= 2) OR (i = 5) OR (i = 7) Then
        strRange = ("A:D")
    Else
        strRange = ("A:A")
    End If

    xlRefSheets = ClientSheets(i)
    With xlRefSheets
        .Cells.EntireColumn.AutoFit()
        .Range(strRange).EntireColumn.Hidden = True
    End With
  Next i

Upvotes: 2

Related Questions