Autofilter with column formatted as date

前端 未结 10 1707
遥遥无期
遥遥无期 2020-11-27 21:58

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

10条回答
  •  醉梦人生
    2020-11-27 22:22

    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)

    1. 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
    

提交回复
热议问题