简体   繁体   English

如何使用VBA在Excel的单个列中过滤多个条件?

[英]How do you use VBA to filter for multiple criteria in a single column in Excel?

I expected the code below to work because it came from a well-rated answer . 我希望下面的代码能正常工作,因为它来自经过良好评价的答案

If this is a formatting error I would like to correct the error rather than completely changing the approach of the solution. 如果这是格式错误,我想纠正错误,而不是完全改变解决方案的方法。 If this way of doing things will not work at all then I am open to trying different approaches. 如果这种处理方式根本不起作用,那么我愿意尝试其他方法。

Any insights would be much appreciated! 任何见解将不胜感激!

 ActiveSheet.Range("$A:$AI").AutoFilter Field:=11, Criteria1:=Array("Namib", "Kitchen", _
                            "Constantia", "Painters", _
                            "CUSTOM", "Classic", _
                            "Bench"), _
            Operator:=xlFilterValues

You can only filter 2 criteria with wildcards: 您只能使用通配符过滤2个条件:

Range("$A:$AI").AutoFilter Field:=11, Criteria1:="=*Table*", Operator:=xlOr, Criteria2:="=*Chair*"

Will filter all data containing the word Table or Chair . 将过滤所有包含单词TableChair But this does not work for more than 2 criteria. 但这不适用于2个以上的条件。

'THIS DOES NOT WORK:
Range("$A:$AI").AutoFilter Field:=11, Criteria1:=Array("*Namib*", "*Kitchen*", _
   "*Constantia*", "*Painters*", _
   "*CUSTOM*", "*Classic*", _
   "*Bench*"), _
     Operator:=xlFilterValues

See: Set Auto Filtering multiple wildcards for a workaround. 请参阅: 设置自动过滤多个通配符以获取解决方法。

Here's another workaround: 这是另一个解决方法:

Sub FilterMultipleWildcards()
    Dim myCriteria As Variant, criterium As Variant
    Dim filteredRng As Range

    myCriteria = Array("Namib", "Kitchen", "Constantia", "Painters", "CUSTOM", "Classic", "Bench")

    With ActiveSheet
        With Intersect(.UsedRange, .Range("$A:$AI"))
            Set filteredRng = .Offset(, .Columns.Count).Resize(1, 1)
            For Each criterium In myCriteria
                .AutoFilter Field:=11, Criteria1:="=*" & criterium & "*"
                If Application.WorksheetFunction.Subtotal(103, .Resize(1)) > 1 Then Set filteredRng = Union(filteredRng, .Resize(.Rows.Count - 1, 1).Offset(1, 10).SpecialCells(xlCellTypeVisible))
            Next
            Set filteredRng = Intersect(filteredRng, .Cells)
            .Parent.AutoFilterMode = False
            .Resize(.Rows.Count - 1).Offset(1).EntireRow.Hidden = True
        End With
        filteredRng.EntireRow.Hidden = False
    End With
End Sub

whose limitation resides in the "capacity" of the range resulting from Union() method 其限制在于Union()方法产生的范围的“容量”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM