在数组中搜索下一个实例

问题描述 投票:1回答:1
For i = 1 To max
    matchFoundIndex = Application.Match(arr(i), arr, 0)
Next

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

arrays vba excel-vba search optimization
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.