首页 > 解决方案 > 使用多个变量VBA自动过滤

问题描述

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

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 会返回过滤结果。我怎样才能让它消除空白变量的错误?

标签: excelvbavariablesfilteringautofilter

解决方案


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

选项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

推荐阅读