简体   繁体   English

VBA自动筛选-条件=数组。 如果数组留空则全选

[英]VBA AutoFilter - Criteria = Array. Select all if array is left blank

I have a macro that I am using to AutoFilter a range based on data entered into multiple cells. 我有一个宏,用于根据输入到多个单元格中的数据自动过滤范围。 Cell A2 contains the text "Enter Zip Code" and the Zip Code is to be entered in B2. 单元格A2包含文本“输入邮政编码”,并且要在B2中输入邮政编码。 Cell A4 contains the text "Enter Service(s)" and the Service is to be entered in B4,B5,B6,and B7. 单元格A4包含文本“输入服务”,并且该服务将在B4,B5,B6和B7中输入。

If I leave cells B4,B5,B6, and B7 blank, the filter does not return any data. 如果我将单元格B4,B5,B6和B7留空,则过滤器不会返回任何数据。 However, I am trying to have the filter select all if those cells are blank. 但是,如果这些单元格为空,我试图让过滤器选择全部。 I originally had cell B4 as a drop down with the 5 possible selections, and I used the following code to select all if left blank: 我最初使用单元格B4作为下拉菜单,其中包含5种可能的选择,并且我使用以下代码选择了所有空白(如果留空):

My_Range.AutoFilter Field:=11, Criteria1:="=" & Range("B2").Value
My_Range.AutoFilter Field:=1, Criteria1:=IIf(Trim(Range("B4").Value) = "", "<>", "=") & Range("B4").Value

However, I would like the option to filter various combinations based on what data is entered into those cells (B4,B5,B6,B7). 但是,我希望选择基于将哪些数据输入到那些单元格(B4,B5,B6,B7)中来过滤各种组合的选项。 In order to do this I changed the code to the following: 为了做到这一点,我将代码更改为以下代码:

My_Range.AutoFilter Field:=11, Criteria1:="=" & Range("B2").Value
My_Range.AutoFilter Field:=1, Criteria1:=Array(Range("B4").Value, Range("B5").Value, Range("B6").Value, Range("B7").Value), Operator:=xlFilterValues

This code gives me the desired result, but if the cells are left blank, the filter does not return anything since it is searching for empty cells in the "Service" column in the range. 这段代码给了我想要的结果,但是如果单元格留为空白,则过滤器不会返回任何内容,因为它正在搜索范围内“服务”列中的空单元格。

Is there a way to use the Array for the Criteria but select all if blank? 有没有一种方法可以将数组用于条件,但是如果全部为空,则选择全部?

Just test for the condition you wish to trap: 只需测试您希望捕获的条件:

If Len([B4] & [B5] & [B6] & [B7]) = 0 Then
    My_Range.AutoFilter Field:=1
Else
    My_Range.AutoFilter Field:=1, Criteria1:=Array(Range("B4").Value, Range("B5").Value, Range("B6").Value, Range("B7").Value), Operator:=xlFilterValues
End If

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

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