使用 Scripting.Dictionary 獲取唯一值

Dictionary 允許非常簡單地獲得一組獨特的值。考慮以下功能:

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
    Next
    Unique = dict.Keys
End Function

然後你可以像這樣呼叫:

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

uniqueVals 只包含 {1,2,3}

注意:此函式可與任何可列舉物件一起使用。