VBA字典是重复的键

有麻烦,需要一些帮助。 我创build了一个简单的例子来学习VBA中的字典,并且已经遇到了一个问题。 我有以下设置:

在这里输入图像说明

我正在尝试循环键,添加键和项目。 如果密钥存在,我想添加项目。 发生什么事是钥匙得到重复。 在下面的例子中,我最终得到了2个苹果,而不是1个。我做错了什么? 任何帮助是极大的赞赏。 相关代码如下:

Dim wkb As Workbook Dim ws As Worksheet Dim dict As Scripting.Dictionary Set wkb = ActiveWorkbook Set ws = wkb.ActiveSheet 'clearing old totals ws.Range("C8:C9").ClearContents Set dict = New Scripting.Dictionary dict.CompareMode = vbTextCompare For i = 3 To 6 If dict.Exists(ws.Cells(i, "B").Value) = False Then MsgBox "doesnt exist, adding " & ws.Cells(i, "B") dict.Add ws.Cells(i, "B"), ws.Cells(i, "C") ElseIf dict.Exists(ws.Cells(i, "B").Value) Then MsgBox "exists" dict.Item(ws.Cells(i, "B")) = dict.Item(ws.Cells(i, "B")) + ws.Cells(i, "C").Value End If Next i MyArray = dict.Keys MsgBox "Keys are: " & Join(MyArray, ";") MyArray = dict.Items MsgBox "Items are: " & Join(MyArray, ";") For Each k In dict.Keys ws.Range("C8") = ws.Range("C8") + dict.Item(k) If k = "Apples" Then ws.Range("C9") = ws.Range("C9") + dict.Item(k) End If Next 

您目前正在添加单元格作为关键字,而不是单元格的Value ,单元格B6不是单元格B3 – 它们至less具有不同的.Row属性。

您应该将您的代码更改为:

 For i = 3 To 6 If dict.Exists(ws.Cells(i, "B").Value) = False Then MsgBox "doesnt exist, adding " & ws.Cells(i, "B").Value dict.Add ws.Cells(i, "B").Value, ws.Cells(i, "C").Value ElseIf dict.Exists(ws.Cells(i, "B").Value) Then MsgBox "exists" dict.Item(ws.Cells(i, "B").Value) = dict.Item(ws.Cells(i, "B").Value) + ws.Cells(i, "C").Value End If Next i