Filter a date or between 2 dates using a macro in an excel report

In most of my reports, I have always minimum one date column, it can be a start date, complete date, end date, etc. and I need to filter it. For instance, I want to filter all problem tickets created on a specific date. This macro will show how to do it but also, I will let you know how to filter between 2 specific dates.

macro excel macro excel macro excel

 

When I use the macro ?

To filter my date column.

 

How to create the macro ?

Read How to create, edit, hide and select a macro in an excel report

 

How to create the button to associate it with the macro ?

Read How to create a button and associated it to a macro in an excel report

 

How to use the macro ?

I have to filter first the column if not, the macro will not work.

 

How is/are the macro(s) ?

Copy the code below and paste it into your macro. You will see my comments in green if exist so follow the help to adapt to your need.

Simple filtering:


Sub test()
Dim i As Date
Dim j As Date
' B1 is the cell containing my date reference 
i = Range("B1").Value
' 4 is to tell to filter 4 days before my date reference 
j = i - 4
' change the range B4:B16 but don’t include the title row of your date column you want to filter
' change the field number 2 (column B) by the date column number you want to filter
Range("B4:B16").AutoFilter Field:=2, Criteria1:=">=" & CDbl(j)
End Sub

Filtering between 2 dates:


Sub test()
Dim i As Date
Dim StartDate As Date
Dim EndDate As Date
' B1 is the cell containing my date reference 
i = Range("B1").Value
' 4 is to tell that my start date will be 4 days before my date reference 
StartDate = i – 4
' 6 is to tell that my end date will be 6 days after my date reference 
EndDate = i + 6
' change the range B4:B16 but don’t include the title row of your date column you want to filter
' change the field number 2 (column B) by the date column number you want to filter
Range("B4:B16").AutoFilter Field:=2, Criteria1:=">=" & CDbl(StartDate), Operator:=xlAnd, Criteria2:="<=" & CDbl(EndDate)
End Sub

Interesting Topics