首页 > 解决方案 > VBA:如何在列中获取唯一值并将其插入到数组中?

问题描述

我已经看到了有关此主题的多个代码,但我似乎无法理解。

例如,如果我有一列记录人员姓名,我想将所有唯一姓名记录到数组中。

所以如果我有一列名字

David
Johnathan
Peter
Peter
Peter
Louis
David

我想利用 VBA 从列中提取唯一名称并将其放入数组中,因此当我调用数组时它会返回这些结果

Array[0] = David
Array[1] = Johnathan
Array[2] = Peter
Array[3] = Louis

标签: vbaexcel

解决方案


尽管 aCollection被提及并且是一种可能的解决方案,但使用 a 的效率要高得多,Dictionary因为它有一个Exists方法。然后只需将名称添加到字典中(如果它们不存在),然后在完成后将键提取到数组中。

请注意,我已使名称比较区分大小写,但如果需要,您可以将其更改为不区分大小写。

Option Explicit

Sub test()

   'Extract all of the names into an array
    Dim values As Variant
    values = Sheet1.Range("Names").Value2 'Value2 is faster than Value

    'Add a reference to Microsoft Scripting Runtime
    Dim dic As Scripting.Dictionary
    Set dic = New Scripting.Dictionary

    'Set the comparison mode to case-sensitive
    dic.CompareMode = BinaryCompare

    Dim valCounter As Long
    For valCounter = LBound(values) To UBound(values)
        'Check if the name is already in the dictionary
        If Not dic.Exists(values(valCounter, 1)) Then
            'Add the new name as a key, along with a dummy value of 0
            dic.Add values(valCounter, 1), 0
        End If
    Next valCounter

    'Extract the dictionary's keys as a 1D array
    Dim result As Variant
    result = dic.Keys

End Sub

推荐阅读