excel - 使用多个变量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 会返回过滤结果。我怎样才能让它消除空白变量的错误?
解决方案
试试这个代码(未测试):
选项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
推荐阅读
- python - 让被调用的方法处理调用者类可以处理的业务是一种不好的做法吗?
- java - 如何使登录错误(“错误的用户名/密码”)在登录页面中更具体
- c - 试图理解 C 语法
- reactjs - 为什么要创建上下文而不仅仅是导出对象?
- typescript - 如何创建一个不会丢失泛型类型参数的类型保护
- javascript - 如果 GeoJson 属性为空,如何使 Leaflet 的 onEachFeature 下的此方法产生不同的结果?
- android - Room Repository:按 ID 选择一行
- python - 如何使用带有 Dask 的正则表达式删除行?
- jwt - 在将 JWKS 与 Auth0 一起使用时,如果我使用的是 localhost,那么受众和发行者是什么?
- node.js - Parse Server 平台 Live Query 是否适合私人聊天?