在数组中搜索下一个实例

时间:2018-03-06 15:20:20

标签: arrays vba excel-vba search optimization

For i = 1 To max
    matchFoundIndex = Application.Match(arr(i), arr, 0)
Next

以上代码返回arr(i)arr的第一次出现。但是,arr(i)中可能存在arr的其他实例。简而言之,如何在arr(i)中有效地找到arr的下一个实例(避免经典的n ^ 2循环)?

1 个答案:

答案 0 :(得分:1)

你可以"隐藏"找到每个匹配项并继续使用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