I got a problem using AutoFilter with VBA in Excel.
It works well for regular filters, but filtering the date column does not work as intended. The column is formatted as date, I can filter it manually and absurdly, 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 starts filtering correctly.
Here is my code:
ws.ListObjects(SheetName).Range.AutoFilter Field:=3, Criteria1 _
:=">" & CDate([datecell]), Operator:=xlAnd, Criteria2:= _
"<=" & CDate(WorksheetFunction.EoMonth([datecell], 3))
Anyone has an idea? It seems to be a common problem, but I have not found a solution.
Thanks in advance.
Edit: Just to add, when I macro record it and run the recorded macro, it does not work either.
here's the occam's razor solution... try putting this in Autoopen for the spreadsheet or if you need to, modify it for the sheet that you wish to affect. it will cause the drop down filters for the date headers to appear as individual dates and not as a date hierarchy.
ActiveWindow.AutoFilterDateGrouping = False
SO this worked for me pretty clean
You can try this as well
Expected output will start date in my G1 cell and end date will be H1 cell.
Karlos Henrique, Thanks for suggesting Format([datecell], "mm/dd/yyyy"). It works in my file. My previous code is :
My modified code is :
Thanks.
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"
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.
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.
Autofilter()
works with 'universal' formatyyyy-mm-dd
, i.e.:It's better because Excel can't 'understand' it wrong . If you use
mm/dd/yyyy
ordd/mm/yyyy
Excel can fit 02/jan as 01/feb.see: http://www.oaltd.co.uk/ExcelProgRef/Ch22/ProgRefCh22.htm
Edit:
We can create an universal Function using
Application.International
like: