VBA字典是复制键

时间:2017-03-23 19:00:28

标签: excel vba excel-vba dictionary

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

enter image description here

我试图循环键,添加键和项目。如果密钥存在,我想将项添加到它。相反,正在发生的是Key的重复。在下面的示例中,我最终得到了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

1 个答案:

答案 0 :(得分:5)

您当前正在添加单元格作为键,而不是单元格的Route,而单元格B6不是单元格B3 - 它们至少具有不同的Route::get('foo', 'SomeController@method'); Route::get('foo', function(){ return view('some.view'); }; 属性。

您应该将代码更改为:

Value