excel 具有多个条件的日期筛选器(XlDynamicFilterCriteria)

lymnna71  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(197)

我正在尝试用2个条件筛选列。我需要这个月和上个月的所有数据。
什么是工作:一个单一的标准,运算符是“xlFilterDynamic”

Sub filtertest()
    Dim LastMonth As XlDynamicFilterCriteria
    LastMonth = xlFilterLastMonth
    
    Dim ThisMonth As XlDynamicFilterCriteria
    ThisMonth = xlFilterThisMonth
    
    ActiveSheet.Range("A1:B92").AutoFilter Field:=1, Criteria1:=ThisMonth, Operator:=xlFilterDynamic
End Sub

结果:

什么是不工作:两个条件,运算符仍然是“xlFilterDynamic”,但这可能不正确。我把这两个条件放到一个数组中。错误1004

Sub filtertest_withArray()

    Dim LastMonth As XlDynamicFilterCriteria
    LastMonth = xlFilterLastMonth
    
    Dim ThisMonth As XlDynamicFilterCriteria
    ThisMonth = xlFilterThisMonth
    
    Dim arrCriteria() As Variant
    ReDim arrCriteria(0 To 1)
    arrCriteria(0) = LastMonth
    arrCriteria(1) = ThisMonth
    
    ActiveSheet.Range("A1:B92").AutoFilter Field:=1, Criteria1:=arrCriteria(), Operator:=xlFilterDynamic
End Sub

但是如果我将Operator设置为“xlFilterValues”,它会运行而不会出错,但是所有的数据集都会被过滤掉。

edit:当我将过滤器设置为这个时,它也不起作用。它只会过滤上个月的日期。

Criteria1:=LastMonth, Operator:=xlFilterDynamic, Criteria2:=ThisMonth, Operator:=xlFilterDynamic
enyaitl3

enyaitl31#

Sub FilterLastAndCurrentMonths()
    Dim lastDayOfCurrentMonth As Variant
    Dim lastDayOfLastMonth As Variant
    
    With Application
        lastDayOfCurrentMonth = Format(.WorksheetFunction.EoMonth(Date, 0), "mm/dd/yyyy")
        lastDayOfLastMonth = Format(.WorksheetFunction.EoMonth(Date, -1), "mm/dd/yyyy")
    End With

    ActiveSheet.Range("$D$3:$D$50").AutoFilter Field:=1, Operator:= _
        xlFilterValues, Criteria2:=Array(1, lastDayOfLastMonth, 1, lastDayOfCurrentMonth)
        
End Sub

qmelpv7a

qmelpv7a2#

我不认为你需要动态的标准来实现你正在(曾经)寻求实现的目标。
在下面的示例中,使用AND运算符在两个日期条件之间进行搜索。

'Establish criteria bounds
Dim startDate As Date, endDate As Date
startDate = DateSerial(Year(Date), Month(Date) - 1, 1)
endDate = DateSerial(Year(Date), Month(Date) + 1, 0)

'Clear filter
ActiveSheet.Range("A1:B92").AutoFilter Field:=1

'Set Filter
ActiveSheet.Range("A1:B92").AutoFilter Field:=1, Criteria1:= _
    ">=" & startDate, Operator:=xlAnd, Criteria2:="<=" & endDate

使用表过滤的一个很好的方法是记录一个宏,手动设置过滤器,然后查看记录的代码。

相关问题