Home > Software engineering >  VBA Date Range Not Filtering
VBA Date Range Not Filtering

Time:12-01

There are many QA on this topic but nothing seems to answer this simple question. I'm not sure why this is code is not working - All I need to do is filter column Q with a date range. What happens is this removes (filters) all items; it does not leave the date range selected:

Dim StDate As Date
Dim EndDate As Date

StDate = "1/20/21"
EndDate = "2/2/21"

With ActiveSheet

.Range("Q1:Q2500").AutoFilter 1, ">=" & StDate, xlAnd, "<=" & EndDate

End With

CodePudding user response:

Filter Between Dates

Option Explicit

Sub FilterBetweenDates()
    
    Const Crit1 As String = ">=1/20/21"
    Const Crit2 As String = "<=2/2/21"
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' be more specific
    
    If ws.AutoFilterMode Then ' remove possbile previous filter
        ws.AutoFilterMode = False
    End If
    
    Dim rg As Range: Set rg = ws.Range("Q1:Q2500")
    
    rg.AutoFilter 1, Crit1, xlAnd, Crit2
    
End Sub
  • Related