vba: get unique values from array

前端 未结 9 2096
北恋
北恋 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:07

    This post contains 2 examples. I like the 2nd one:

    Sub unique() 
      Dim arr As New Collection, a 
      Dim aFirstArray() As Variant 
      Dim i As Long 
    
      aFirstArray() = Array("Banana", "Apple", "Orange", "Tomato", "Apple", _ 
      "Lemon", "Lime", "Lime", "Apple") 
    
      On Error Resume Next 
      For Each a In aFirstArray 
         arr.Add a, a 
      Next 
    
      For i = 1 To arr.Count 
         Cells(i, 1) = arr(i) 
      Next 
    
    End Sub 
    
    0 讨论(0)
  • 2020-11-22 16:08

    No, nothing built-in. Do it yourself:

    • Instantiate a Scripting.Dictionary object
    • Write a For loop over your array (be sure to use LBound() and UBound() instead of looping from 0 to x!)
    • On each iteration, check Exists() on the dictionary. Add every array value (that doesn't already exist) as a key to the dictionary (use CStr() since keys must be strings as I've just learned, keys can be of any type in a Scripting.Dictionary), also store the array value itself into the dictionary.
    • When done, use Keys() (or Items()) to return all values of the dictionary as a new, now unique array.
    • In my tests, the Dictionary keeps original order of all added values, so the output will be ordered like the input was. I'm not sure if this is documented and reliable behavior, though.
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题