vba: get unique values from array

前端 未结 9 2266
北恋
北恋 2020-11-22 15:30

Is there any built-in functionality in vba to get unique values from a one-dimensional array? What about just getting rid of duplicates?

If not, then how would I get

9条回答
  •  庸人自扰
    2020-11-22 15:58

    The Collection and Dictionary solutions are all nice and shine for a short approach, but if you want speed try using a more direct approach:

    Function ArrayUnique(ByVal aArrayIn As Variant) As Variant
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' ArrayUnique
    ' This function removes duplicated values from a single dimension array
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim aArrayOut() As Variant
    Dim bFlag As Boolean
    Dim vIn As Variant
    Dim vOut As Variant
    Dim i%, j%, k%
    
    ReDim aArrayOut(LBound(aArrayIn) To UBound(aArrayIn))
    i = LBound(aArrayIn)
    j = i
    
    For Each vIn In aArrayIn
        For k = j To i - 1
            If vIn = aArrayOut(k) Then bFlag = True: Exit For
        Next
        If Not bFlag Then aArrayOut(i) = vIn: i = i + 1
        bFlag = False
    Next
    
    If i <> UBound(aArrayIn) Then ReDim Preserve aArrayOut(LBound(aArrayIn) To i - 1)
    ArrayUnique = aArrayOut
    End Function
    

    Calling it:

    Sub Test()
    Dim aReturn As Variant
    Dim aArray As Variant
    
    aArray = Array(1, 2, 3, 1, 2, 3, "Test", "Test")
    aReturn = ArrayUnique(aArray)
    End Sub
    

    For speed comparasion, this will be 100x to 130x faster then the dictionary solution, and about 8000x to 13000x faster than the collection one.

提交回复
热议问题