The dataset showcases Order ID, Product, and Delivery Date.
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.
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
- 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.
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.
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
- 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
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!