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
Autofilter()
works with 'universal' format yyyy-mm-dd
, i.e.:
Criteria1:= ">" & Format([MY_DATE],"yyyy-mm-dd")
Criteria2:= "<=" & Format([MY_DATE],"yyyy-mm-dd")
It's better because Excel can't 'understand' it wrong . If you use mm/dd/yyyy
or dd/mm/yyyy
Excel can fit 02/jan as 01/feb.
see: http://www.oaltd.co.uk/ExcelProgRef/Ch22/ProgRefCh22.htm
The Rules for Working with Excel (International Issue)
- When you have to convert numbers and dates to strings for passing to Excel (such as in criteria for AutoFilter or .Formula strings), always explicitly convert the data to a US-formatted string, using Trim(Str(MyNumber)), or the sNumToUS() function shown earlier, for all number and date types. Excel will then use it correctly and convert it to the local number/date formats.
Edit:
We can create an universal Function using Application.International
like:
Sub MySub()
Select Case application.International(xlDateOrder)
Case Is = 0
dtFormat = "mm/dd/yyyy"
Case Is = 1
dtFormat = "dd/mm/yyyy"
Case Is = 2
dtFormat = "yyyy/mm/dd"
Case Else
dtFormat = "Error"
End Select
Debug.Print (dtFormat)
...
Criteria1:= ">" & Format([MY_DATE],dtFormat)
Criteria2:= "<=" & Format([MY_DATE],dtFormat)
...
End Sub
Karlos Henrique, Thanks for suggesting Format([datecell], "mm/dd/yyyy"). It works in my file. My previous code is :
Range("A1:D" & Trim(Str(LstRec))).AutoFilter Field:=2, _
Criteria1:=">=" & StrtDt, _
Operator:=xlAnd, _
Criteria2:="<=" & EndDt
My modified code is :
Range("A1:D" & Trim(Str(LstRec))).AutoFilter Field:=2, _
Criteria1:=">=" & Format(StrtDt, "mm/dd/yyyy"), _
Operator:=xlAnd, _
Criteria2:="<=" & Format(EndDt, "mm/dd/yyyy")
Thanks.
I had similar problem, while filtering column with date. When I changed system date format to 01/01/2020, it converted my date to 1/1/2020 in Criteria field. My solution was to convert arguments to str during setting to function.
One solution is to set up correctly the format of the target column. If its formatted as "custom", even if it looks like a date, it won't work.
You are asking VBA to filter based on a date, therefore the format of the columns has to be a date too.