2016-07-27 69 views
0

Data to Filter直到結束

嗨,

我創建鏈接到一個腳本宏文件複製AutoFiltered數據環路。我希望它從第一個會計年度過濾財務年度列,並將其複製到另一個表格,然後循環直到處理完所有會計年度。

我在模塊中做了一個重複的操作,但如果我刪除了一個會計年度,它將不會繼續。

如何過濾可用會計年度的標準,並且會循環直至結束?我的問題是下面的代碼,因爲它只指定一個會計年度。

ActiveSheet.Range( 「$ A $ 1:$ d $ 20」),自動篩選字段:= 3,標準1:= 「2012」

謝謝!

回答

0

下面的代碼將幫助您循環遍歷年份過濾器。

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 
+0

謝謝夏嘉曦瑞士雷達表對您有所幫助。這適用於我的宏。由於我遇到「編譯錯誤變量未定義」,我只刪除了Option Explicit。我還想問一下,如果在某個財政年度沒有數據,我該如何確定它會進入下一個財政年度? – cameri

+0

@cameri查看編輯後的代碼,它將循環使用多年並過濾表格,稍後它會顯示每年有多少行。如果它是0,或者它不是0,我不確定你想要做什麼? –

+0

如果它是0,我希望它進入下一個財政年度。如果它不是0,那麼就按照原樣繼續直到結束。提前致謝。 :) – cameri