在应用了另一个过滤器之后,前n个值的Excel过滤器

时间:2019-11-24 15:43:39

标签: excel vba

我一直在努力理解为什么excel会以这种方式行事,但似乎找不到简单的解释: 为什么在应用了另一个过滤器之后,我不能对前n个项目进行过滤?我正在尝试使用以下公式通过VBA进行此操作,但它仅过滤单个值。手动过滤也会产生相同的结果:

.AutoFilter Field:=10, Criteria1:=">=" & Date - 3
.AutoFilter Field:=35, Criteria1:="10", Operator:=xlTop10Items

为什么Excel会以这种方式表现?解决方案是什么?

2 个答案:

答案 0 :(得分:1)

常规过滤器检查整个表,而不仅仅是检查的行。我猜想要添加该功能,就必须有有关应用不同列过滤器的顺序的信息。又或者是设计使然,将每个列过滤器作为AND类型的操作来应用。

有几种选择:

  1. 对值使用公式条件的高级过滤器
  2. 使用Power Query,其中的后续过滤器将依赖于先前的操作。

我建立了一个包含两列DateValue的简单表。标头位于A7:B7

enter image description here

有两列条件

enter image description here

Formula:  =B8>=AGGREGATE(14,4,(Table1[Date]>=(TODAY()-3))*Table1[Value],10)
Date:  =">="&TODAY()-3

执行高级过滤器后:

enter image description here

这里是上述2列表的VBA代码示例。您需要根据实际数据进行调整。请注意,在VBA代码中,我没有使用Table引用,但是您可以根据需要更改它。

Option Explicit
Sub specialFilter()
    Dim WB As Workbook, WS As Worksheet
    Dim dataRng As Range, critRng As Range
    Dim datesRng As Range, valuesRng As Range

'Set ranges
Set WB = ThisWorkbook
Set WS = WB.Worksheets("sheet1")
With WS
    Set dataRng = .Range(.Cells(7, 1), .Cells(.Rows.Count, 2).End(xlUp))
    Set datesRng = .Range(.Cells(8, 1), .Cells(.Rows.Count, 1).End(xlUp))
    Set valuesRng = .Range(.Cells(8, 2), .Cells(.Rows.Count, 2).End(xlUp))
    Set critRng = .Range(.Cells(1, 1), .Cells(2, 2))
End With

'enter criteria
With critRng
    .Cells(1, 1).Value = "Formula"
    .Cells(2, 1).Formula = "=B8>=AGGREGATE(14,4,(" & datesRng.Address & ">=(TODAY()-3))*" & valuesRng.Address & ",10)"
    .Cells(1, 2).Value = dataRng.Cells(1, 1) 'must be same as column header
    .Cells(2, 2).Formula = "="">="" & TODAY()-3"
End With

If WS.FilterMode = True Then WS.ShowAllData
dataRng.AdvancedFilter _
    Action:=xlFilterInPlace, _
    criteriarange:=critRng, _
    Unique:=False
End Sub

另一个选项是高级查询 (在Excel 2010和更高版本中可用) 不幸的是,无法从GUI设置条件,而是需要使用“高级编辑器”。

M代码

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Date", type date}, {"Value", Int64.Type}}),
    #"Filtered Rows" = Table.SelectRows(#"Changed Type", each [Date] >= Date.AddDays( DateTime.Date(DateTime.FixedLocalNow()),-3)),
    #"Filtered Rows1" = Table.SelectRows(#"Filtered Rows", each [Value] >= List.Min(List.MaxN(#"Filtered Rows"[Value],10)))
in
    #"Filtered Rows1"

答案 1 :(得分:-1)

let todaysSchedules = schedules.filter(value => {
  return today.isBetween(
    parseInt(value.T_START)*1000,
    parseInt(value.T_END)*1000,
    "day",
    "[]"
  )
});

结束子

希望您知道如何更改页面引用。您还可以使用类似...的标识最后一行。

LastRow = sht.Cells(sht.Rows.Count,“ A”)。End(xlUp).Row

the而不是Range(..... 使用Cell(lastrow,[column#]).....

应该可以带您去想要的地方。