vba: get unique values from array

前端 未结 9 2300
北恋
北恋 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 16:10

    There's no built-in functionality to remove duplicates from arrays. Raj's answer seems elegant, but I prefer to use dictionaries.

    Dim d As Object
    Set d = CreateObject("Scripting.Dictionary")
    'Set d = New Scripting.Dictionary
    
    Dim i As Long
    For i = LBound(myArray) To UBound(myArray)
        d(myArray(i)) = 1
    Next i
    
    Dim v As Variant
    For Each v In d.Keys()
        'd.Keys() is a Variant array of the unique values in myArray.
        'v will iterate through each of them.
    Next v
    

    EDIT: I changed the loop to use LBound and UBound as per Tomalak's suggested answer. EDIT: d.Keys() is a Variant array, not a Collection.

提交回复
热议问题