VBA Collection.Add不工作

时间:2016-11-01 11:47:05

标签: vba excel-vba excel

我有一个集合来从数组中获取唯一值,但由于某种原因它会通过数组但最终显示的集合

该集合的代码是:

Dim Materials as Variant
Dim Unique as New Collection, a

On Error Resume Next
For Each a In Materials
    Unique.Add a, a
Next

任何人都可以提供有关为什么这不起作用的见解吗?

1 个答案:

答案 0 :(得分:2)

如果你真的想要一个集合(例如,你想要按照它们第一次出现的顺序保留这些项目),在构建集合时使用字典作为临时数据结构仍然是个好主意。类似的东西:

$user_roles->first()->display_name

测试如下:

Function Uniques(A As Variant) As Collection
    Dim D As Object, C As New Collection
    Set D = CreateObject("Scripting.Dictionary")
    Dim v As Variant

    For Each v In A
        If Not D.exists(v) Then
            D.Add v, 1
            C.Add v
        End If
    Next v

    Set Uniques = C
End Function

输出:

Sub test()
    Dim Materials As Variant, C As Collection, v As Variant
    Materials = Array(2, 3, 5, 2, 6, 5, 7, 4, 2)
    Set C = Uniques(Materials)
    For Each v In C
        Debug.Print v
    Next v
End Sub

如果您想要的只是一个类似于集合的对象而不是集合本身,您可以完全跳过该集合,只需2 3 5 6 7 4 (适当修改)返回字典本身。