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
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
No, nothing built-in. Do it yourself:
Scripting.Dictionary
objectFor
loop over your array (be sure to use LBound()
and UBound()
instead of looping from 0 to x!)Exists()
on the dictionary. Add every array value (that doesn't already exist) as a key to the dictionary (CStr()
since keys must be stringsScripting.Dictionary
), also store the array value itself into the dictionary.Keys()
(or Items()
) to return all values of the dictionary as a new, now unique array.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.