I'm using the below code to get the count of the filtered data rows in VBA, but while getting the count, it's giving the run time error showing:
"Object required".
Could some please let me know what change(s) is needed?
Set rnData = .UsedRange
With rnData
.AutoFilter Field:=327, Criteria1:=Mid(provarr(q), 1, 2)
.Select
.AutoFilter Field:=328, Criteria1:=Mid(provarr(q), 3, 7)
.Select
.AutoFilter Field:=330, Criteria1:=Mid(provarr(q), 10, 2)
.Select
.AutoFilter Field:=331, Criteria1:=Mid(provarr(q), 12, 2)
.Select
Rowz = .AutoFilter.Range.SpecialCells(xlCellTypeVisible).Rows.count
....
End With
If you try to count the number of rows in the already autofiltered range like this:
Rowz = rnData.SpecialCells(xlCellTypeVisible).Rows.Count
It will only count the number of rows in the first contiguous visible area of the autofiltered range. E.g. if the autofilter range is rows 1 through 10 and rows 3, 5, 6, 7, and 9 are filtered, four rows are visible (rows 2, 4, 8, and 10), but it would return 2 because the first contiguous visible range is rows 1 (the header row) and 2.
A more accurate alternative is this (assuming that ws
contains the worksheet with the filtered data):
Rowz = ws.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1
We have to subtract 1 to remove the header row. We need to include the header row in our counted range because SpecialCells will throw an error if no cells are found, which we want to avoid.
The Cells
property will give you an accurate count even if the Range has multiple Areas, unlike the Rows
property. So we just take the first column of the autofilter range and count the number of visible cells.
Simply put this in your code:
Application.WorksheetFunction.Subtotal(3, Range("A2:A500000"))
Make sure you apply the correct range, but just keep it to ONE column
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With