如何获得一组独特的值?

时间:2015-09-16 21:01:24

标签: vba vbscript vb6

给定某种值集合(数组或某种集合),如何生成一组不同的值?

1 个答案:

答案 0 :(得分:1)

使用Scripting.Dictionary工具 - > 引用... - > Microsoft Scripting Runtime ):

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上运行VBA(没有Microsoft Scripting Runtime),则可以使用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