简体   繁体   中英

Filter between 2 date ranges

I would like to filter 1 lot of data between 2 date ranges.

Date range 1: Going back from yesterday's date to 28 days previous.
Date range 2: Going back one year from yesterday's date to 28 days previous.

To filter to one date range I have this code working:

Sub DateFilter()

Dim StartDateTY As Date
Dim EndDateTY As Date
StartDateTY = Date - 29
EndDateTY = Date - 1

Sheets("Main").Range("$A$4:$O$5000").AutoFilter Field:=2, _
 Criteria1:=">=" & CDbl(StartDateTY), Operator:=xlAnd, _
 Criteria2:="<=" & CDbl(EndDateTY)

End Sub

I was thinking I could use arrays to use 2 different date ranges but can't get it working.

Sub DateFilter2Ranges()

Dim StartDateTY As Date
Dim EndDateTY As Date
StartDateTY = Date - 29
EndDateTY = Date - 1

Dim StartDateLY As Date
Dim EndDateLY As Date
StartDateLY = Date - 29 - 365
EndDateLY = Date - 1 - 365

Sheets("Main").Range("$A$4:$O$5000").AutoFilter Field:=2, _
  Criteria1:=Array(0, ">=" & CDbl(StartDateTY), 0, ">=" & CDbl(StartDateLY)), Operator:=xlAnd, _
  Criteria2:=Array(1, "<=" & CDbl(EndDateTY), 1, "<=" & CDbl(EndDateLY))

End Sub

I also thought I could mix 'And' & 'Or' operators if this is possible.

In order to work with dates in autofilter, you need to know one thing - autofilter recognizes only US date format: month/day/year .

Sub FFF()

    Dim dt1 As Date, dt2 As Date
    Dim sDate1$, sDate2

    '// Get dates
    dt1 = Now - 29: dt2 = Now - 1

    '// Format dates
    sDate1 = Format(dt1, "MM\/yy\/yyyy")
    sDate2 = Format(dt2, "MM\/yy\/yyyy")

    With Sheets("Main").Range("A1").CurrentRegion
        .AutoFilter
        .AutoFilter Field:=2, Criteria1:=">=" & sDate1, Operator:=xlAnd, Criteria2:="<=" & sDate2

    End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM