vba Excel:使用多个条件过滤:自动过滤器或高级过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42803528/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:17:47  来源:igfitidea点击:

Excel : filter with Multiple Criteria : AutoFilter or AdvancedFilter

excelvbaexcel-vbaautofilteradvanced-filter

提问by Mathew Hood

I am trying to create a filter that will do the below

我正在尝试创建一个过滤器,它将执行以下操作

Begins with "4" or Contains "2TWH" or Contains "2TER"

以“4”开头或包含“2TWH”或包含“2TER”

I believe it will turn out to look like this

我相信它会变成这样

ActiveSheet.Range("$A:$H").AutoFilter Field:=2, Criteria1:="=4*", _
    Operator:=xlOr, Criteria2:="=*2TWH*" 

but I need to somehow also have a criteria 3 for ="=2TER"

但我需要以某种方式对 ="= 2TER"也有一个标准 3

I did some googling and saw that you can store the values into an array and then call the array values but I was unable to get them into the array in a usable fashion.

我做了一些谷歌搜索,发现您可以将值存储到数组中,然后调用数组值,但我无法以可用的方式将它们放入数组中。

Is anyone able to offer some assistance with this please?

有没有人可以提供一些帮助?

采纳答案by R3uK

This should do the trick :

这应该可以解决问题:

ActiveSheet.Range("$A:$H").AutoFilter Field:=2, Criteria1:="=4*", _
    Operator:=xlOr, Criteria2:=Array("*2TWH*","*2TER*")

This doesn't throw any error, but ...
it'll only take 2 criteria because there are wildcards (*).
Here it's the last criteria from the array (here *2TER*)

这不会引发任何错误,但...
这将只需要2个标准,因为有通配符(*)。
这是数组中的最后一个条件 (here *2TER*)



Ideally, this would have been nice, as it works for constants,
but because you use WildCards (*) it only supports 2 criteria... :/

理想情况下,这会很好,因为它适用于constants
但是因为您使用 WildCards ( *) 它只支持 2 个条件...:/

ActiveSheet.Range("$A:$H").AutoFilter Field:=2, Criteria1:=Array("*2TWH*", "*2TER*", "4*"), _
    Operator:=xlFilterValues




So you'll have to go with AdvancedFilter:

所以你必须去AdvancedFilter

With ActiveSheet
    'Const xlFilterInPlace = 1
    .Range("$A:$H").AdvancedFilter _
                        Action:=xlFilterInPlace, _
                        CriteriaRange:=WsFilterSettings.Range("A1:A4")
End With 'ActiveSheet

AdvancedFiltertake a Range as criteria inputs, CriteriaRange, so you'll have to put on a sheet:

AdvancedFilter范围作为条件输入CriteriaRange因此您必须放在一张纸上

  • the header of the columnyou want to apply to the filter on
  • your criteriabelow the respective header (if you have multiples columns)
  • 要应用于过滤器的列标题
  • 您在相应标题下方的标准(如果您有多个列)

Each COLUMNof that Range, are linkedby an AND
Each ROWof that Range, are linkedby an OR
So build your table carefully!

每个COLUMN这个范围的,都
每个ROW这个范围的,都OR
所以精心打造你的表!

In the above example code, I have used :
(let's say that your column's headerwas Column To Filter On) :

在上面的示例代码中,我使用了 :(
假设您的列标题Column To Filter On):

A1 | Column To Filter On
A2 | 4*
A3 | *2TWH*
A4 | *2TER*