在数组中搜索下一个实例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在数组中搜索下一个实例相关的知识,希望对你有一定的参考价值。
For i = 1 To max
matchFoundIndex = Application.Match(arr(i), arr, 0)
Next
上面的代码返回arr(i)
中第一次出现的arr
。但是,在arr(i)
中可能存在arr
的其他情况。简而言之,我怎样才能在arr(i)
中有效地找到arr
的下一个实例(避免经典的n ^ 2循环)?
答案
你可以“隐藏”找到的所有匹配并继续使用Application.Match()
:
Function GetIndexes(arr As Variant) As String
Dim tempArr As Variant, matchIndex As Variant, element As Variant
Dim matchIndexes As String
tempArr = arr ' use a temporary array not to spoil the passed one
For Each element In tempArr
If element <> "|||" Then 'skip elements already marked as "already found"
matchIndexes = ""
matchIndex = Application.Match(element, tempArr, 0) 'search for array element matching current one
Do
matchIndexes = matchIndexes & matchIndex & " "
tempArr(matchIndex - 1) = "|||" 'mark found array element as "already found"
matchIndex = Application.Match(element, tempArr, 0) 'search for next array element matching current one
Loop While Not IsError(matchIndex) ' loop until no occurrences of current array element
GetIndexes = GetIndexes & "element '" & element & "' found at indexes: " & Replace(Trim(matchIndexes), " ", ",") & vbCrLf
End If
Next
End Function
你可以利用如下:
Sub main()
Dim i As Long
Dim arr As Variant
arr = Array("a1", "a2", "a3", "a1", "a2", "a3")
MsgBox GetIndexes(arr)
End Sub
以上是关于在数组中搜索下一个实例的主要内容,如果未能解决你的问题,请参考以下文章