将字符串数组连接为过滤条件的多个条件

时间:2019-06-25 09:46:37

标签: excel vba

我想在自动筛选器中串联一个字符串数组。

我只是使用宏记录器来编写此代码。

我正试图获得与此相同的输出,并且我不想暴力破解所有可能的条件。

 ActiveSheet.Range("$A$8:$BH$331").AutoFilter Field:=4, Criteria1:=Array( _
    "ISO 14001","ISO 45001", "ISO 9001", "OHSAS 18001", "QMET"), Operator:=xlFilterValues

但是如果条件满足,我需要将每个文本连接起来。

Dim strStandard(0 To 5) As String    
strStandard(0) = "ISO 9001"
strStandard(1) = "ISO 14001"
strStandard(2) = "ISO 45001"
strStandard(3) = "QMET"
strStandard(4) = "OHSAS 18001"
strStandard(5) = "Combined (14K+18K)
If ISO9001.Value = True = True Then
    ActiveSheet.Range("$A$8:$BH$331").AutoFilter Field:=4, Criteria1:=ISO9001.Value
End If
If ISO14001.Value = True = True Then
 ActiveSheet.Range("$A$8:$BH$331").AutoFilter Field:=4, Criteria1:= _
   "ISO 14001"
End If

strStandard将是过滤器的多个条件

我的想法是检查每个复选框的值是否为true(如果为true),它将从strStandard数组获取字符串,并将其传递给strFilterContainer以获取字符串数组,然后将其传递给单个Autofilter

ActiveSheet.Range("$A$8:$BH$331").AutoFilter Field:=4, Criteria1:=strFilterContainer, Operator:=xlFilterValues

strStandard将是过滤器的多个条件 有没有办法在自动过滤器内部串联字符串数组?

1 个答案:

答案 0 :(得分:0)

本质上,您需要使用正确的值填充Array。要获得正确大小的数组,可以使用ReDimSplit

使用Redim

Dim MyFilters() As String, ArrayLength As Long
ArrayLength = -1
If ISO9001.Value Then
    ArrayLength = ArrayLength+1
    'Resize the array
    ReDim Preserve MyFilters(0 to ArrayLength)
    'Add option to the end of the array
    MyFilters(ArrayLength) = "ISO 9001"
End If
If ISO14001.Value Then
    ArrayLength = ArrayLength+1
    'Resize the array, without clearing contents
    ReDim Preserve MyFilters(0 to ArrayLength)
    'Add option to the end of the array
    MyFilters(ArrayLength) = "ISO 14001"
End If
If ISO45001.Value Then
    ArrayLength = ArrayLength+1
    'Resize the array, without clearing contents
    ReDim Preserve MyFilters(0 to ArrayLength)
    'Add option to the end of the array
    MyFilters(ArrayLength) = "ISO 45001"
End If
'Et Cetera

'If we have items in the Filter
If ArrayLength >= 0 Then
    'Apply the Filter
    ActiveSheet.Range("$A$8:$BH$331").AutoFilter Field:=4, _
        Criteria1:=MyFilters, Operator:=xlFilterValues
End If

使用Split

Dim FilterString As String
FilterString = ""

'Add the items to the string
If ISO9001.Value Then FilterString = FilterString & "|ISO 9001"
If ISO14001.Value Then FilterString = FilterString & "|ISO 14001"
If ISO45001.Value Then FilterString = FilterString & "|ISO 45001"
'Et Cetera

'If we have items in the Filter
If Len(FilterString) > 0 Then
    'Remove the first "|"
    FilterString = Mid(FilterString, 2)
    'Apply the Filter
    ActiveSheet.Range("$A$8:$BH$331").AutoFilter Field:=4, _
        Criteria1:=Split(FilterString,"|"), Operator:=xlFilterValues
End If

我个人会使用Split,因为它比ReDim的资源消耗少