不确定这是否会有所帮助——例如,如果您AutoFilter
出于某种原因实际需要该方法,这可能不会削减它。但是,如果您只是在寻找一种方法来找到所有匹配的单元格,那么这应该可以工作,并且它将为您提供一种迭代这些单元格范围的方法。
在示例中,字典将匹配单元格的地址存储为Key
值,并将匹配单元格的地址存储.Row.Address
为Item
值。
然后,您可以遍历字典中的Keys
或Items
以使用这些范围/地址。
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")