在细胞数据的日期范围内进行了自动或自动过滤

时间:2017-10-07 14:44:41

标签: excel vba date input filter

我有一张表(Sheet1),其中列i是日期字段。我想创建一个宏,要求输入开始日期和结束日期,将这些日期放在两个单元格中,例如i38,i39,然后在这些单元格中使用该数据进行过滤。这可能吗?

我是宏和VB的新手,无法弄清楚如何在基于日期的过滤器中使用单元格数据。

感谢您的帮助。

1 个答案:

答案 0 :(得分: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)