VBA筛选条件并遍历行

我正在阅读许多练习册,每本练习册都有超过5万行。 但是我只需要某些行的数据。 当我在工作簿中时,我正在尝试根据条件进行筛选,然后仅循环这些行,但不起作用。

ActiveSheet.ShowAllData 'Remove All Filters lastrow_ = ws.Range("A" & Rows.Count).End(xlUp).row ActiveSheet.Range("A2" & lastrow_).AutoFilter Field:=1, Criteria1:="=1" 'Filter on the Criteria 'Set The Range Set rng = Range("A1:P" & Cells(Rows.Count,"A").End(xlUp).row).SpecialCells(xlCellTypeVisible) 'Loop through the range For each row in rng 'do stuff 

我已经在另一个代码片段中定义了行。 但是这不起作用。 它不循环只在filter中应用的行。 有什么build议么? 谢谢!!!

因为AutoFilter可能会产生一个不连续的范围,所以你需要循环AreasRanges ,像这样

 Dim ar as Range, row As Range, rng As Range Ws.ShowAllData 'Remove All Filters lastrow_ = ws.Range("A" & Rows.Count).End(xlUp).row Ws.Range("A2" & lastrow_).AutoFilter Field:=1, Criteria1:="=1" 'Filter on the Criteria 'Set The Range Set rng = ws.Range("A1:P" & Cells(Rows.Count,"A").End(xlUp).row).SpecialCells(xlCellTypeVisible) 'Loop through the range For Each ar in rng.Areas For Each row in ar.Rows 'do stuff Next row, ar