【问题标题】:Autofiltering with multiple variables VBA使用多个变量VBA自动过滤
【发布时间】:2021-11-01 21:36:38
【问题描述】:

所以我试图在同一列上过滤多个变量。我使用带有产品选择的用户表单:

If PT1.value = True Then
ProductType1 = "Product 1"
Else
ProductType1 = ""
End If
If PT2.Value = True Then
ProductType2 = "Product 2"
Else
ProductType2 = ""
End If
If PT3.Value = True Then
ProductType3 = "Product 3"
Else
ProductType3 = ""
End If
        
    If ProductType <> "" Then
        TD.Range("A3:BL3").AutoFilter Field:=7, Criteria1:=Array("*" & ProductType1 & "*", "*" & ProductType2 & "*", "*" & ProductType3 & "*"), Operator:=xlFilterValues
        End If

本质上,如果他们选择 PT1,那么第一个变量将变为 ProductType1,依此类推

如果 producttype1 和 producttype2 有值,但 producttype3 没有,则它不会返回任何内容,但是,从代码中删除 producttype 3 会返回过滤结果。我怎样才能让它消除空白变量的错误?

【问题讨论】:

  • 张贴您的表格的一部分,包括字段 7,以及一些更清晰的示例。
  • 这里的问题是“Criteria1 数组”仅限于接受两个带有通配符的元素。一种解决方法,如果您对隐藏行感到满意,可以循环遍历列的单元格并将匹配的单元格组合到一个范围中,最后隐藏组合范围的整个行。另一种解决方法是,如果您有一列具有唯一值,则循环遍历条件列的单元格,并在每次匹配时将唯一列的相应值写入数组(字典),然后按此数组过滤(字典: dict.Keys) 在唯一列中。

标签: excel vba variables filtering autofilter


【解决方案1】:

试试这个代码(未测试):

选项 1

Sub test1()
    Const delim = "|"
    Dim s As String: s = ""
    
    If PT1.Value Then s = s & "Product 1"
    If PT2.Value Then s = s & IIf(s = "", "", delim) & "Product 2"
    If PT3.Value Then s = s & IIf(s = "", "", delim) & "Product 3"
        
    If s <> "" Then
        TD.Range("A3:BL3").AutoFilter Field:=7, Criteria1:=Split(s, delim), Operator:=xlFilterValues
    End If
End Sub

选项 2

Sub test2()
    If PT1.Value Or PT2.Value Or PT3.Value Then
        TD.Range("A3:BL3").AutoFilter Field:=7, Operator:=xlFilterValues, _
            Criteria1:=Array(IIf(PT1.Value, "Product 1", Empty), _
                             IIf(PT2.Value, "Product 2", Empty), _
                             IIf(PT3.Value, "Product 3", Empty))
    End If
End Sub

【讨论】:

  • 感谢您的回复。不幸的是,我已经意识到(以及其他评论)自动过滤时我不能有超过 2 个通配符
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
相关资源
最近更新 更多