VBA 自动过滤器排除多个条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45421061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Autofilter exclude multiple criteria
提问by James Steele
I need to exclude multiple criteria from a range. The code below does not error but it does not filter out all values (e.g "ZL1" is still in the range). I have tried Operator:=xlAnd but the result is no different. With Operator:=xlFilterValues I get "Run-time error '1004': AutoFilter method of Range class failed.
我需要从一个范围中排除多个条件。下面的代码不会出错,但不会过滤掉所有值(例如“ZL1”仍在范围内)。我试过 Operator:=xlAnd 但结果没有什么不同。使用 Operator:=xlFilterValues 我得到“运行时错误‘1004’:Range 类的自动筛选方法失败。
Sub Macro1()
Sheets("Z").Select
myarr = Array("<>ZC1", "<>ZL1", "<>ZF1")
lr = Range("A" & Rows.Count).End(xlUp).Row
ActiveSheet.Range("$A:$M$" & lr).AutoFilter Field:=3, Operator:=xlOr, Criteria1:=(myarr)
End Sub
回答by takanuva15
As Ibo mentioned in comments above, you can't use AutoFilter directly like that to exclude 3 or more values. This particular postis relevant to your situation. Here's an example way to do it:
正如 Ibo 在上面的评论中提到的,您不能像那样直接使用 AutoFilter 来排除 3 个或更多值。这篇特定的帖子与您的情况有关。这是一个示例方法:
- In cell O2, put
=ISNA(MATCH(C2, $P$2:$P$4,0))
. - In P2 through P4, put your filter values ZC1, ZL1, and ZF1 in separate cells.
- 在单元格 O2 中,输入
=ISNA(MATCH(C2, $P$2:$P$4,0))
。 - 在 P2 到 P4 中,将过滤器值 ZC1、ZL1 和 ZF1 放在单独的单元格中。
Then run this macro:
然后运行这个宏:
Sub Macro2()
lr = Range("A" & Rows.Count).End(xlUp).Row
Range("$A:$M$" & lr).AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:=Range("O1:O2"), Unique:=False
End Sub
Before running macro:
运行宏之前:
After AdvancedFilter macro:
在 AdvancedFilter 宏之后: