下面的代碼將幫助您循環遍歷年份過濾器。
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