【发布时间】:2019-08-10 23:36:27
【问题描述】:
我有一系列数据,其中每个项目都有许多与之关联的值。项目块将共享这些值,然后对于其他项目,这些值会改变。
我正在数据库之间传输数据。在旧版本中,每个项目的所有值都单独存储。在新数据库中,我想通过将这些值集存储为配置来利用大量项目共享相同值的事实。我在 vba for excel 中这样做。
为了确定唯一的值集是什么,我想使用一个字典,其中键是一个集合。由于它允许我这样做,我陷入了一种错误的安全感,但是它无法识别密钥相同的位置。
示例代码如下。应该只在字典中添加两项,但添加所有 3。我是否遗漏了某些内容或只是对字典有太多期望?如果我不必手动比较所有集合,可以节省我一点时间。
Sub CollectionAsKeyTest()
Dim dic As New Dictionary
Dim col As Collection
Dim i As Integer
dic.CompareMode = BinaryCompare
'Create a collection to add to dictionary:
Set col = New Collection
For i = 1 To 10
col.Add i * 1
Next i
dic.Add col, "item 1"
'Create a different collection and add as key to dictionary:
Set col = New Collection
For i = 1 To 10
col.Add i * 2
Next i
If Not dic.Exists(col) Then dic.Add col, "item 2"
'Create a collection which is the same as the first, and try to add to dictionary:
Set col = New Collection
For i = 1 To 10
col.Add i * 1
Next i
If Not dic.Exists(col) Then dic.Add col, "item 3"
'All three collections are added:
Debug.Print "Number of collections added = " & dic.count
End Sub
【问题讨论】:
-
每次 col 都是一个新集合,因此它不会存在于您的字典中。
-
它每次都是一个新的集合,但包含相同的数据。这不是一样吗?
-
为什么将集合存储为
Key?将您的收藏存储为Value,将您的Value存储为Key -
当对象相同时,它们是相等的。例如,
Range("A1")与Range("A2")不同,即使Range("A1").Value = Range("A2").Value也是如此。集合就是对象。 -
@SJR 我想是的,尽管您可以进行实验。就个人而言,我从不使用既不是字符串也不是数字的键的 VBA 字典,正是因为语义有点不直观。我不是 100% 确定如何对集合进行哈希处理以获取密钥。 This question 讨论它。
标签: excel vba dictionary collections