Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip first element in the range in a For Each loop statement?

Tags:

excel

vba

The thing I want to do is relatively simple. I have a data set which I filtered based on a criteria, hence hiding some of the rows in my worksheet. I set a range for my filtered data which should only go through cells that are visible with sample code.

With MyDataWorksheet.AutoFilter.Range
     On Error Resume Next
     Set AutoFilterRange = .SpecialCells(xlCellTypeVisible)
     On Error GoTo 0
End With

Now I would like to loop through all my data in the AutoFilterRange variable which should have captured all rows that are visible. I Loop through them doing something like this.

Sub aSub()

Dim DR As Range
For Each DR In AutoFilterRange
    'Do something here
Next DR

End Sub

I use this for each loop to do stuff with the visible rows, however I would like to just skip the first element in the data range as this element row number contains my header names. I thought doing something like this would help solve my problem, but all it does is go to the next hidden row element right after the header row element.

For Each DR In AutoFilterRange.Offset(1,0)
    'Do something here
Next DR
like image 321
DSM Avatar asked Jan 27 '23 00:01

DSM


2 Answers

You could add an if statement and a "flag".

Sub aSub()

Dim DR As Range
Dim flag as Boolean
flag = false
For Each DR In AutoFilterRange
    If flag = true Then
        'Do something here
    End If
    flag = true
Next DR

End Sub

This will skip the first iteration due to flag is false, then I set it to true and it will do something on all the other iterations.

like image 144
Andreas Avatar answered Jan 31 '23 10:01

Andreas


Something like this

With MyDataWorksheet
    If .AutoFilterMode Then
        With .AutoFilter.Range
            Set AutoFilterRange = .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).SpecialCells(xlCellTypeVisible)
        End With
    End If
End With

In your code you don't show what AutoFilterRange would be if AutoFilter is not On, so I also skip that part.

like image 40
buran Avatar answered Jan 31 '23 11:01

buran