我在尝试理解以下代码时遇到困难。我在以下链接中找到了它:vba: get unique values from array
Dim d As Object
Set d = CreateObject("Scripting.Dictionary")
'Set d = New Scripting.Dictionary
Dim i As Long
For i = LBound(myArray) To UBound(myArray)
d(myArray(i)) = 1
Next i
Dim v As Variant
For Each v In d.Keys()
'd.Keys() is a Variant array of the unique values in myArray.
'v will iterate through each of them.
Next v
编辑:我很理解整个代码,但是我不明白最后一部分。
Dim v As Variant
For Each v In d.Keys()
'd.Keys() is a Variant array of the unique values in myArray.
'v will iterate through each of them.
Next v
我听不懂这行
d(myArray(i)) = 1
编辑:我正在寻找执行相同目标的代码,但我希望完全了解我要应用的内容,而不是仅复制并粘贴我不了解的内容。
更具体地说,我正在构造宏中的几个元素,而这正是我要寻找的元素。
该宏将帮助我完成第4点。一旦我确定了少于4个的项目,我需要找到这些项目,并尝试将它们与另一张纸上的项目进行匹配。我需要使用上面的代码,因为我宁愿在宏中使用数组而不是Excel本身中的函数,以免因幻影图形对用户造成混淆。
答案 0 :(得分:2)
按部分划分:
Dim d As Object
Set d = CreateObject("Scripting.Dictionary")
'Set d = New Scripting.Dictionary
这将创建字典对象
Dim i As Long
For i = LBound(myArray) To UBound(myArray)
d(myArray(i)) = 1
Next i
对于字典对象,有两种添加新项的方法:
d.Add Key, Value
如果字典中已有该键,则此方法将导致错误
d(Key) = Value
从技术上讲,此方法是对指定键的值的重新分配。如果键不存在,则会隐式添加。如果键已经存在,则值将被更新。
那么代码在做什么,是循环遍历数组中的每个值,以及:
使用当前字典键(数组的值)将当前索引重新分配为字典值
如果该密钥尚不存在,请创建它。
这将导致字典中每个唯一值具有一个键。只需将所有重复的值重新分配给现有键的值,而不是创建新的键。
Dim v As Variant
For Each v In d.Keys()
'd.Keys() is a Variant array of the unique values in myArray.
'v will iterate through each of them.
Next v
详细说明:d.Keys
以数组的形式返回字典中的所有键。由于键是myArray
的唯一值,因此d.Keys
是myArray
的唯一值的数组。