VBA过滤字符串类型中的多个条件

时间:2013-05-23 02:50:58

标签: string excel vba autofilter

我正在尝试为自动过滤器编写代码,目的是过滤大约10个条件,每个条件都是M1454之类的字符串(换句话说,只要数据包含{{1}然后它将被过滤)。但我在使用数组作为字符串条件时遇到问题。以下是我使用的准确标准的代码:

M1454

但是,如果我将条件从Sub AutoFilter() 'Select the whole worksheet for filter' ActiveWorkbook.ActiveSheet.Range("A:BB").Select 'Set the condition for BType' Selection.AutoFilter Field:=15, Criteria1:=Array( _ "M1454H", "M1643D", "M1670D", "M1736A", "M1747B", "M1747C", _ "M1766B", "M1796B", "M1796Z", "M1867A", "M1867B", "M1947B", _ "M2617A", "M4886A"), Operator:=xlFilterValues End Sub 更改为M1454H,则会显示错误。有谁知道为什么会这样,谢谢:)

1 个答案:

答案 0 :(得分:0)

不确定这是否有帮助 - 例如,如果您出于某种原因需要AutoFilter方法,这可能不会削减它。但是,如果您只是想找到一种方法来查找所有匹配的单元格,这应该可行,并且它将为您提供迭代这些单元格范围的方法。

在示例中,字典将匹配单元格的地址存储为Key值,将匹配单元格的.Row.Address存储为Item值。

然后,您可以遍历字典中的KeysItems以使用这些范围/地址。

Option Explicit
Sub GetFilteredRangeCells()

'REQUIRES REFERENCE TO MICROSOFT SCRIPTING RUNTIME LIBRARY

Dim rng As Range  '## The range you want to filter
Dim firstFound As Range '## to use with the .Find method
Dim fndRange As Range '## to use with the .Find method
Dim f As Long '## column # that is being filtered on
Dim filteredDict As New Scripting.Dictionary
Dim dictKey As Variant
Dim dictItem As Variant
Dim crit As Variant '## use this to iterate filterCriteria array

'## establish an array of values to filter, modify as needed ##'
Dim filterCriteria(1 To 3) As Variant 
    filterCriteria(1) = "*1414*"
    filterCriteria(2) = "*B*"
    filterCriteria(3) = "*Jo*"

    Set rng = Range("A1:B82") '## The range to search
    f = 1  '## Modify as needed, this will search the first column


    For Each crit In filterCriteria

        Set firstFound = Nothing 'clear out this variable
        Set firstFound = rng.Columns(1).Find(crit, After:=rng.Cells(f, 1), _
                LookIn:=xlValues, SearchDirection:=xlNext)    'find the first match

        'if any match is found, then find the rest
        If Not firstFound Is Nothing Then
            Set fndRange = firstFound
            Do
                Set fndRange = rng.Columns(f).FindNext(fndRange)
                'Duplicates are not allowed in a Dictionary:
                If Not filteredDict.Exists(fndRange.Address) Then
                    filteredDict.Add fndRange.Address, rng.Rows(fndRange.Row).Address
                End If
            Loop While Not fndRange.Address = firstFound.Address
        End If
    Next

    '## You can then iterate over the Keys, as needed:
    For Each dictKey In filteredDict.Keys
        Debug.Print dictKey & " -- "; filteredDict.Item(dictKey)
    Next

    Set filteredDict = Nothing
End Sub

注意:这要求您添加对Microsoft Scripting Runtime库的引用。如果你不能这样做,那么你可以这样修改代码,它仍然可以工作:

Dim filteredDict as Object
Set filteredDict = CreateObject("Scripting.Dictionary")