2017-10-07 65 views
-1

我有一個工作表(Sheet1),其中第i列是日期字段。我想創建一個宏,要求輸入開始日期和結束日期,將這些日期放在兩個單元格中,比如i38,i39,然後在那些單元格中使用該數據進行過濾。這可能嗎?從單元格數據日期範圍內的Advaned或自動篩選

我是新來的宏和VB,並不能找出如何使用基於日期的過濾器中的單元格數據。

感謝您的任何幫助。

回答

0

開始:

enter image description here

運行以下命令:

Sub FilterDateRange() 
    Dim d1 As String, d2 As String, r As Range 
    Set r = Range("I1:I26") 

    d1 = ">" & Application.InputBox(Prompt:="enter start date", Type:=2) 
    d2 = "<" & Application.InputBox(Prompt:="enter start date", Type:=2) 

    r.AutoFilter 
    r.AutoFilter Field:=1, Criteria1:=d1, Operator:=xlAnd, Criteria2:=d2 

    Range("I38") = Mid(d1, 2) 
    Range("I39") = Mid(d2, 2) 
End Sub 

可生產:

enter image description here

編輯#1:

包括端點(不僅僅是端點之間),使用這些代碼行:

d1 = ">=" & Application.InputBox(Prompt:="enter start date", Type:=2) 
d2 = "<=" & Application.InputBox(Prompt:="enter start date", Type:=2) 
+0

真棒,我會嘗試很快。如果這是一個巨大的文件,有沒有辦法從上到下選擇第一列而不是使用範圍?而不是將輸入安裝到單元中,是否可以在代碼中使用它們而不記錄它們?我忘了需要這個過濾器的實際文件有多大。而且尺寸每個月都有所不同。 – 12fretter

+0

@ 12fretter要過濾整個列,請使用此行***設置r =範圍(「I:I」)***而不是發佈行............然後刪除最後兩行上面的代碼行結束Sub *** –

+0

完美!非常感謝。 – 12fretter