Filter Criteria1 and Criteria 2 undefined on column of Dates

被刻印的时光 ゝ 提交于 2021-02-11 12:40:16

问题


According to Microsoft: https://docs.microsoft.com/en-us/office/vba/api/excel.filter.criteria2 It is possible to set a variable = .Criteria2. This throws a runtime 1004 error in Excel 2010-2019/365.

Note: if the filtered column is dates, Criteria1 and Criteria2 are undefined: Application-Defined or Object-Defined Error. Note: Excel will correctly remember Criteria1 when filtering a column of text or numbers.

To simplify this for reviewers, I simply recorded a macro filtering a column of dates and added comments to show the results.

Sub Macro2()
'
' Macro2 Macro
'
Dim testfilter As Variant
Dim testfilter2 As Variant

' I recorded filtering Column A and removing a few dates

    ActiveSheet.Range("$A$1:$M$51").AutoFilter Field:=1, Criteria1:=Array("=") _
        , Operator:=xlFilterValues, Criteria2:=Array(0, "6/7/2021", 0, "10/27/2020", 0, _
        "11/16/2019", 1, "3/30/2018", 1, "5/17/2018", 1, "6/30/2018", 1, "7/28/2018", 1, _
        "9/3/2018", 1, "10/31/2018", 1, "12/29/2018")
    Set WS = ActiveSheet
    With WS.AutoFilter
       With .Filters(1)
         If .On And .Operator Then
            testfilter = .Criteria1 ' Criteria1 = "="
            testfilter2 = .Criteria2 ' Runtime Error 1004 - Application-Defined or object-defined error
        End If
       End With
    End With

End Sub

回答1:


If one uses Excel’s date filters, Criteria1 and Criteria2 are defined and can be assigned to a variable so that they can be remembered and reapplied.

If one has dates from 2018 to 2020 and unchecks the box next to 2018 in the dropdown filter menu, Excel uses an array for Criteria2, but Criteria2 remains undefined and causes a Runtime Error 1004 if one tries to assign it to a variable.

Workaround: Require use of data filters and use code to detect and handle undefined Criteria1 and Criteria2.

I want to thank ComputerVersteher for all of the help.



来源:https://stackoverflow.com/questions/63494607/filter-criteria1-and-criteria-2-undefined-on-column-of-dates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!