尝试这个。您可以将其用作数组公式,选择合理数量的单元格来显示结果,或者在代码中使用它并以您喜欢的任何方式转储到工作表中。
它接受要搜索的单个字符串(它会拆分并测试单个字符串中的每个单词),然后是要搜索的字符串、范围或数组的 Param 数组。它返回一个匹配数组,因此您可以将其用作数组公式或在代码中用作任何其他数组。
使用示例:
=GetAllMatches("two three",A1:A5)
具有单个连续范围的示例
=GetAllMatches("two three",A1,A3:A20,B5:B8,D1)
'非连续单元格的例子
=GetAllMatches("two three",{"one two","three two","one two three"})
数组示例
=GetAllMatches("two three","one two","one","three two","one two three")
字符串示例
For each match in GetAllMatches(blah,blahblah):Debug.Print match:Next match
在代码中而不是公式中使用的示例
您可能需要调整口味,但我已经评论了它在代码中的作用。
代码示例:
Public Function GetAllMatches(searchFor As String, ParamArray searchWithin()) As Variant
'I use a ParamArray to handle the case of wanting to pass in non-contiguous ranges to search other
'e.g. Blah(A1,A2,A3,C4:C10,E5)
'nice little feature of Excel formulae :)
Dim searchRange, arr, ele, searchComponents
Dim i As Long
Dim results As Collection
Dim area As Range
Set results = New Collection
'generate words to test
searchComponents = Split(searchFor, " ")
For Each searchRange In searchWithin
If TypeOf searchRange Is Range Then 'range (we test to handle user passing in arrays)
For Each area In searchRange.Areas 'we enumerate to handle multi-area ranges
arr = area.Value
If VarType(arr) < vbArray Then 'we test to handle single cell areas
If isMatch(arr, searchComponents) Then results.Add arr 'is a match so add to results
Else 'is an array, so enumerate
For Each ele In arr
If isMatch(ele, searchComponents) Then results.Add ele 'is a match so add to results
Next ele
End If
Next area
Else
Select Case VarType(searchRange)
Case Is > vbArray 'user passed in an array not a range
For Each ele In searchRange 'enumerate, not iterate, to handle multiple dimensions etc
If isMatch(ele, searchComponents) Then results.Add ele 'is a match so add to results
Next ele
Case vbString
If isMatch(searchRange, searchComponents) Then results.Add searchRange 'is a match so add to results
Case Else 'no idea - return an error then fail fast (suppressed if called by an excel formula so ok)
GetAllMatches = CVErr(XlCVError.xlErrRef)
Err.Raise 1, "GetAllMatches", "Invalid Argument"
End Select
End If
Next searchRange
'Process Results
If results.Count = 0 Then 'no matches
GetAllMatches = CVErr(XlCVError.xlErrNA) 'return #N/A
Else
'process results into an array
ReDim arr(0 To results.Count - 1)
For i = 0 To UBound(arr)
arr(i) = results(i + 1)
Next i
GetAllMatches = arr 'Return the array of matches
End If
End Function
Private Function isMatch(ByRef searchIn, ByRef searchComponents) As Boolean
Dim ele
For Each ele In searchComponents
If Not (InStr(1, searchIn, ele, vbTextCompare) > 0) Then
Exit Function
End If
Next ele
isMatch = True
End Function
电子表格示例:
one
one two
one two three
one three two
four three one two
结果:
one two three
one three two
four three one two