0

我正在尝试为自动过滤器编写代码,目的是过滤大约 10 个条件,每个条件都是一个字符串,例如M1454(换句话说,只要数据包含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*M1454*则会出现错误。有谁知道为什么会这样,谢谢:)

4

1 回答 1

0

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

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

然后,您可以遍历字典中的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")
于 2013-05-23T14:40:10.243 回答