Using a VBA Code to Filter Data by Date in Excel – 4 Examples

The dataset showcases Order ID, Product, and Delivery Date.

vba code to filter data by date in excel


Example 1 – Using a VBA Code to Filter Data between Dates in Excel

In the following dataset there is a Start and an End Date.

VBA Code to Filter Data between Dates in Excel

STEPS:

  • Select the sheet and right-click.
  • Select View Code.
  • The VBA window will open.
  • Enter the following code.
Sub BetweenDates()
Dim sDate As Long
Dim EDate As Long
sDate = Range("F5").Value
EDate = Range("G5").Value
Range("D4:D10").AutoFilter 1, ">=" & sDate, xlAnd, "<=" & EDate
End Sub

VBA Code to Filter Data between Dates in Excel

  • Press F5 to run the code.
  • Close the VBA window.

This is the output.


Example 2 – Filtering Data by the Exact Date with Excel VBA

In the dataset below, an exact date was entered in F5.

Filter Data by Exact Date with Excel VBA

STEPS:

  • Select View Code after right-clicking.
  • The VBA window will open.
  • Enter the following code.
Sub FilterByExactDate()
Dim ExactDate As Date
Dim sDate As String
Dim EDate As Long
ExactDate = DateSerial(2022, 2, 5)
EDate = ExactDate
Range("D4:D10").AutoFilter
    Range("D4:D10").AutoFilter Field:=1, Criteria1:=">=" & EDate, _
                     Operator:=xlAnd, Criteria2:="<" & EDate + 1
End Sub

  • Press F5 to run the code.
  • Close the VBA window.

This is the output.


Example 3. Applying a VBA Code to Filter Data before a Specified Date

A specific date was entered in F5.

Apply VBA Code to Filter for Data before Specified One

STEPS:

  • Select View Code after right-clicking.
  • The VBA window will open.
  • Enter the following code.
Sub BeforeDate()
Dim sDate As Long
sDate = Range("F5").Value
Range("D4:D10").AutoFilter 1, "<" & sDate
End Sub

Apply VBA Code to Filter for Data before Specified One

  • Press F5 to run the code.
  • Close the VBA window.

This is the output.


Example 4 – Filtering Data after a Specified Date Using a VBA Code

Filter for Data after Specified Date Using VBA Code

STEPS:

  • Select View Code after right-clicking.
  • The VBA window will open.
  • Enter the following code.
Sub AfterDate()
Dim sDate As Long
sDate = Range("F5").Value
Range("D4:D10").AutoFilter 1, ">" & sDate
End Sub

  • Press F5 to run the code.
  • Close the VBA window.

This is the output.


Download Practice Workbook

Download the following workbook to practice.


<< Go Back to Date Filter | Filter in Excel | Learn Excel

Get FREE Advanced Excel Exercises with Solutions!

Leave a Reply

Your email address will not be published. Required fields are marked *

Advanced Excel Exercises with Solutions PDF