在一列上自动过滤三个日期

时间:2017-02-20 21:28:37

标签: vba

我是Macro的新手,我需要以下代码的帮助。我想在一列上过滤用户提供的三个日期。下面的宏给我空白结果。

Sub newdate()
Dim today As Date, yesterday As Date, tomorrow As Date

    yesterday = CDate(Application.InputBox(Prompt:="Please enter yesterday date:", Type:=2))
    today = CDate(Application.InputBox(Prompt:="Please enter today date:", Type:=2))
    tomorrow = CDate(Application.InputBox(Prompt:="Please enter tomorrow date:", Type:=2))

    ActiveSheet.Range("A:E").AutoFilter Field:=5, Criteria1:="=" & yesterday
    ActiveSheet.Range("A:E").AutoFilter Field:=5, Criteria1:="=" & today
    ActiveSheet.Range("A:E").AutoFilter Field:=5, Criteria1:="=" & tomorrow 

1 个答案:

答案 0 :(得分:0)

要按三个日期过滤,请使用数组作为条件。试试这个。

yesterday = CDate(Application.InputBox(Prompt:="Please enter yesterday date:", Type:=2))
today = CDate(Application.InputBox(Prompt:="Please enter today date:", Type:=2))
tomorrow = CDate(Application.InputBox(Prompt:="Please enter tomorrow date:", Type:=2))
arrDates = Array(yesterday, today, tomorrow)

ActiveSheet.Range("A:E").AutoFilter Field:=5, _
  Criteria1:=arrDates, _
  Operator:=xlFilterValues

顺便说一下你需要询问用户的日期吗?您可以通过日期自动设置今天的日期,并使用DateAdd查找昨天或明天。

yesterday = DateAdd("d", -1, Date)
today = Date
tomorrow = DateAdd("d", 1, Date)
arrDates = Array(yesterday, today, tomorrow)

ActiveSheet.Range("A:E").AutoFilter Field:=5, _
    Criteria1:=arrDates, _ 
    Operator:=xlFilterValues