1

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
paddy
  • 60,864
  • 6
  • 61
  • 103
Jose M.
  • 2,242
  • 8
  • 44
  • 66
  • 3
    `If (i <=2 AndAlso 5 AndAlso 7)` is not going to evaluate the way you probably think it is.... – Tim Sep 26 '13 at 22:25
  • 1
    Please put Option Strict On at the top of your code file or set it in your project's properties. Your If condition should not compile as it is expecting a Boolean expression. – Chris Dunaway Sep 27 '13 at 14:04

1 Answers1

2

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
Ryan
  • 26,884
  • 9
  • 56
  • 83