如何通过VBA自动过滤多个条件

时间:2018-07-19 04:18:58

标签: vba excel-vba

我要过滤4个“或”条件和2个“与”条件。

The string contains both "Bank of America" and "Chargeback"
or contains both "BOFA" and "CHGBK"
or contains both "American Express" and "CHGBCK"
or contains both "BOFA" and "Chargeback"

这意味着总共有4个条件,每个条件必须包含2个字符串。

我附上了代码方面的打击,但是没有用。请指教!非常感谢!

Worksheets("xBofA_Modified").Activate
arr1 = Array("*Bank of America*", "*Chargeback*")
arr2 = Array("*BOFA*", "*CHGBK*")
arr3 = Array("*American Express*", "*CHGBCK*")
arr4 = Array("*BOFA*", "*Chargeback*")

Worksheets("xBofA_Modified").Rows("1:1").AutoFilter Field:=11, _
    Criteria1:=arr1, _
    Operator:=xlOr, _
    Criteria2:=arr2, _
    Operator:=xlOr, _
    Criteria3:=arr3, _
    Operator:=xlOr, _
    Criteria4:=arr4, _
    opertator:=xlFilterValues

1 个答案:

答案 0 :(得分:0)

可悲的是(据我所知),无法使用自动筛选完成此任务。 可以使用变通办法。尝试这样的事情:

Sub main()

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("xBofA_Modified")

Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

Dim cell As Range
For Each cell In Range("K2:K" & lastRow)
    If (InStr(cell.Value, "Bank of America") > 0 And InStr(cell.Value, "Chargeback") > 0) = False And _
       (InStr(cell.Value, "BOFA") > 0 And InStr(cell.Value, "CHGBK") > 0) = False And _
       (InStr(cell.Value, "American Express") > 0 And InStr(cell.Value, "CHGBCK") > 0) = False And _
       (InStr(cell.Value, "BOFA") > 0 And InStr(cell.Value, "Chargeback") > 0) = False _
    Then
        cell.EntireRow.Hidden = True
    End If
Next cell
End Sub

此代码循环遍历K列(第11列)中的每个单元格,然后隐藏不适用于您的任何条件的行。 完成此操作不是很好的解决方案,但结果与使用AutoFilter可获得的结果几乎相同。