2015-09-16 180 views
-1

給定某種值的集合(一個數組或某種集合),我如何生成一組不同的值?如何獲得一組獨特的值?

+1

從[提取唯一值的集合可能重複在VBA過濾器](http://stackoverflow.com/questions/31891059/extracting-the-collection-of-unique-values-from-a-filter-in-vba) – Jeeped

+0

@Jeeped這是爲了表明一般技術,而不需要混合Excel或其他主機特定的代碼。 –

+0

是的,我得到*完全*你正在努力完成的。只是有太多的Scripting.Dictionary示例已經可用了,我懷疑我們是否需要一個非Community-Wiki自我回答的帖子。也許你應該註冊新的[文檔之王](http://meta.stackoverflow.com/questions/306213/warlords-of-documentation-your-questions-answered?cb=1)努力。我有。 – Jeeped

回答

1

使用Scripting.Dictionary工具 - >引用... - >Microsoft腳本運行時):

Function Unique(values As Variant) As Variant() 
    'Put all the values as keys into a dictionary 
    Dim dict As New Dictionary 
    Dim val As Variant 
    For Each val In values 
     dict(val) = 1 
    Next 
    Unique = dict.Keys 'This cannot be done with a Collection, which doesn't expose its keys 
End Function 

在VBScript或VBA,如果你喜歡使用後期綁定(變量,但不顯式類型):

Function Unique(values) 
    Dim dict, val 
    Set dict = CreateObject("Scripting.Dictionary") 
    For Each val In values 
    ... 

如果在Mac(沒有Microsoft腳本運行時)上運行VBA,有一個drop-in replacement for Dictionary可用。

一些例子:


另一種選擇(僅VBA)是使用Collection。這是一個稍微尷尬,因爲沒有辦法設置沒有錯誤的現有密鑰被拋出,因爲返回的數組必須手動創建:

Function Unique(values As Variant) As Variant() 
    Dim col As New Collection, val As Variant, i As Integer 
    For Each val In values 
     TryAdd col, val, val 
    Next 
    Dim ret() As Variant 
    Redim ret(col.Count - 1) 
    For i = 0 To col.Count-1 
     ret(i) = col(i+1) 
    Next 
    Unique = ret 
End Function 

Sub TryAdd(col As Collection, item As Variant, key As String) 
    On Error Resume Next 
    col.Add(item, key) 
End Sub