Forum Discussion
Excel / VBA - filter data and save in new file
This is caused by a quirk of Excel VBA. From Range.Rows property:
"When applied to a Range object that is a multiple selection, this property returns rows from only the first area of the range. For example, if the Range object someRange has two areas A1:B2 and C3:D4, someRange.Rows.Count returns 2, not 4. To use this property on a range that may contain a multiple selection, test Areas.Count to determine whether the range is a multiple selection."
The first time in the loop, the code filters for the first category it encountered, in row 2. So the visible range starts with an area that contains at least rows 1 and 2.
But the second time, row 2 is hidden because the code now filters for another category. So the visible range starts with an area that consists of the header row only, and visibleRange.Rows.Count returns 1.
Solution: change
If Not visibleRange Is Nothing And visibleRange.Rows.Count > 1 Then
to
If Not visibleRange Is Nothing And (visibleRange.Rows.Count > 1 Or visibleRange.Areas.Count > 1) Then
Hi Hans,
Thanks for this. The change in code does not yield the desired outcome. I still have the problem. Did you try the code yourself with the change? If so, please can you let me have the full file?
Thanks,
Naveen
- HansVogelaarJul 20, 2025MVP
Yes, I tested the code. Here is my test workbook with some dummy data. The macro produced multiple files: