简体   繁体   English

VBA使用Excel中的复选框进行过滤?

[英]VBA Filter using checkboxes in Excel?

I'm new to VBA in Excel and trying to build a menu that will allow users to enter filter criteria using checkboxes. 我是Excel中VBA的新手,正在尝试构建一个菜单,允许用户使用复选框输入过滤条件。 In this case, filter by states. 在这种情况下,请按状态过滤。 Everything works fine when there is only one state selected, but multiple states clears the filter. 当仅选择一种状态时,一切正常,但是清除多个状态。 The code I'm using to build the filter criteria string is below. 下面是我用于构建过滤条件字符串的代码。 I've tried adding additional quotes ("AL", "AK") but that clears the filter when only a single state is selected. 我尝试添加其他引号(“ AL”,“ AK”),但是当仅选择单个状态时,这将清除过滤器。 Any suggestions would be greatly appreciated. 任何建议将不胜感激。

If Sheets("Menu").ckAL.Value = True Then
    strCriteria = strCriteria & ", AL"

End If

If Sheets("Menu").ckAK.Value = True Then
    strCriteria = strCriteria & ", AK"

End If

strCriteria = Mid(strCriteria, 2)

ActiveSheet.Range("$A$4:$AR$16998").AutoFilter Field:=3, Criteria1:=Array(strCriteria), Operator:=xlFilterValues

Thanks. 谢谢。

Bruce 布鲁斯

I tested this, and it worked for me. 我对此进行了测试,并且对我有用。 Since the Criteria1 is expecting an array of strings, the strCriteria needs to be split into an array which is then passed into the filter criteria. 由于Criteria1需要一个字符串数组,因此需要将strCriteria拆分为一个数组,然后将其传递到过滤条件中。

If Sheets("Menu").ckAL.Value = True Then
    strCriteria = strCriteria & ", AL"

End If

If Sheets("Menu").ckAK.Value = True Then
    strCriteria = strCriteria & ", AK"

End If

strCriteria = Mid(strCriteria, 2)

ActiveSheet.Range("$A$4:$AR$16998").AutoFilter Field:=3, Criteria1:=Split(strCriteria,", "), Operator:=xlFilterValues

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

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