下面的代码将帮助您循环遍历年份过滤器。
Option Explicit
Sub Loop_FiscalYear()
Dim Sht As Worksheet
Dim Year_Loop As Integer
Dim Year_Start As Integer
Dim Year_Finish As Integer
' modify Sheet1 to your sheet name
Set Sht = ThisWorkbook.Sheets("Sheet1")
' modify these parameters according to your needs
Year_Start = 2012
Year_Finish = 2016
For Year_Loop = Year_Start To Year_Finish
Sht.Range("$A$1:$D$20").AutoFilter Field:=3, Criteria1:=Year_Loop
' do your other stuff here.....
Next Year_Loop
End Sub
编辑1:选项代号2,计数可见的行数,每株滤波年
Sub Loop_FiscalYear()
Dim Sht As Worksheet
Dim Data_Rng As Range
Dim Year_Loop As Integer
Dim Year_Start As Integer
Dim Year_Finish As Integer
Dim VisibleRows As Long
Dim Last_Row As Long
Dim Last_Col As Long
Dim RngArea
' modify Sheet1 to your sheet name
Set Sht = ThisWorkbook.Sheets("Sheet5") ' ("Sheet1")
' remove all filters from table's data
Sht.Range("C1").Select
If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
ActiveSheet.AutoFilter.ShowAllData
End If
' find last row in sheet
Last_Row = Cells(Rows.Count, "A").End(xlUp).row
' find last column in sheet
Last_Col = Cells(1, Columns.Count).End(xlToLeft).Column
Set Data_Rng = Sht.Range(Cells(1, 1), Cells(Last_Row, Last_Col))
' modify these parameters according to your needs
Year_Start = 2012
Year_Finish = 2016
For Year_Loop = Year_Start To Year_Finish
With Data_Rng
.AutoFilter Field:=3, Criteria1:=Year_Loop
.Select
' count number of rows in Filtered area
For Each RngArea In .SpecialCells(xlCellTypeVisible).Areas
VisibleRows = VisibleRows + RngArea.Rows.Count
Next
' MsgBox just for easy debug
MsgBox "Autofilter " & VisibleRows - 1 & " rows "
If VisibleRows = 0 Then
' do something...
End If
End With
' reset value for Next year loop
VisibleRows = 0
Next Year_Loop
End Sub
谢谢夏嘉曦瑞士雷达表对您有所帮助。这适用于我的宏。由于我遇到“编译错误变量未定义”,我只删除了Option Explicit。我还想问一下,如果在某个财政年度没有数据,我该如何确定它会进入下一个财政年度? – cameri
@cameri查看编辑后的代码,它将循环使用多年并过滤表格,稍后它会显示每年有多少行。如果它是0,或者它不是0,我不确定你想要做什么? –
如果它是0,我希望它进入下一个财政年度。如果它不是0,那么就按照原样继续直到结束。提前致谢。 :) – cameri