VBA Scripting.Dictionary object Getting unique values with Scripting.Dictionary


The Dictionary allows getting a unique set of values very simply. Consider the following function:

Function Unique(values As Variant) As Variant()
    'Put all the values as keys into a dictionary
    Dim dict As New Scripting.Dictionary
    Dim val As Variant
    For Each val In values
        dict(val) = 1 'The value doesn't matter here
    Unique = dict.Keys
End Function

which you could then call like this:

Dim duplicates() As Variant
duplicates = Array(1, 2, 3, 1, 2, 3)
Dim uniqueVals() As Variant
uniqueVals = Unique(duplicates)

and uniqueVals would contain only {1,2,3}.

Note: This function can be used with any enumerable object.