Autofilter with column formatted as date

Spurious picture Spurious · Nov 4, 2013 · Viewed 61.8k times · Source

I am using an AutoFilter with VBA in Excel that works for regular filters, but not a column formatted as date.

I can filter it manually. If I run my code, it filters nothing but when I check the filter and then only click ok (no change being applied to the filter criteria), it filters correctly.

Here is my code:

ws.ListObjects(SheetName).Range.AutoFilter Field:=3, Criteria1 _
        :=">" & CDate([datecell]), Operator:=xlAnd, Criteria2:= _
        "<=" & CDate(WorksheetFunction.EoMonth([datecell], 3))

It seems to be a common problem, but I have not found a solution.

When I run a recorded macro, it does not work either.

Answer

Ron Rosenfeld picture Ron Rosenfeld · Nov 4, 2013

Dates can be tricky with Excel VBA AutoFilter. Some find it easier to just loop through the array to be filtered.

Sometimes I have found that one can use the numeric value of the date, especially when dealing with "dates between"

Criteria1:= ">" & CDbl([datecell])
Criteria2:= "<=" & CDbl(WorksheetFunction.EoMonth([datecell], 3))

Note that the above need to be "real dates" and not strings that look like dates. Even a single "string date" will mess things up.