vba - VBA:如何在列中获取唯一值并将其插入到数组中?
问题描述
我已经看到了有关此主题的多个代码,但我似乎无法理解。
例如,如果我有一列记录人员姓名,我想将所有唯一姓名记录到数组中。
所以如果我有一列名字
David
Johnathan
Peter
Peter
Peter
Louis
David
我想利用 VBA 从列中提取唯一名称并将其放入数组中,因此当我调用数组时它会返回这些结果
Array[0] = David
Array[1] = Johnathan
Array[2] = Peter
Array[3] = Louis
解决方案
尽管 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
推荐阅读
- azure-bot-service - 机器人作曲家-发布到 Azure-位置 0 的 JSON 中的意外令牌 E
- php - 如何在单个php页面中调用多个sql存储过程
- c++ - 为什么包含自定义对象的 STL 集需要 operator< 重载,而不是 operator==
- javascript - Node JS + Express JS:从其他位置刷新页面
- flutter - Flutter Item ExpansionPanelList 不会改变状态
- javascript - ReactJS 中的 JQuery:TypeError: jquery__WEBPACK_IMPORTED_MODULE_18___default(...)(...).sortable is not a function
- c++ - 如何将 Raylib 添加到 VS 代码中?
- c++ - Cmake 找不到带有错误消息的库路径
- oauth-2.0 - WSO2 API Manager - 从 API 客户端验证用户
- debian - debian buster/10 iptables raw TRACE,没有日志