如何将多个键和值同时添加到字典中?

时间:2020-02-18 16:17:55

标签: excel vba dictionary

我试图将一列添加为键,并将其右侧的列添加为值。

我可以不循环吗?

我尝试过:

analystDict.Add Key:=refWS.Range("A2:A21"), Item:=refWS.Range("B2:B21")

当我尝试Debug.Print时,出现类型不匹配错误:

For Each x In analystDict.Keys
    Debug.Print x, analystDict(x)
Next x

2 个答案:

答案 0 :(得分:1)

如果不编写帮助函数,则无法在VBA中执行此操作。

Option Explicit

Public Sub AddTest()
    Dim analystDict As Scripting.Dictionary
    Set analystDict = New Scripting.Dictionary

    Dim refWS As Worksheet
    Set refWS = ActiveSheet

    AddToDictionary _
        analystDict, _
        Application.WorksheetFunction.Transpose(refWS.Range("A2:A21").Value), _
        Application.WorksheetFunction.Transpose(refWS.Range("B2:B21").Value)

End Sub

Public Sub AddToDictionary(ByRef ipDict As Scripting.Dictionary, ByVal ipKeys As Variant, ByVal ipValues As Variant)

    If UBound(ipKeys) <> UBound(ipValues) Then

        MsgBox "Arrays are not the same size"
        Exit Function

    End If

    Dim myIndex As Long
    For myIndex = LBound(ipKeys) To UBound(ipKeys)

        ipDict.Add ipKeys(myIndex), ipValues(myIndex)

    Next

End Function

答案 1 :(得分:1)

您正在使用不允许的快捷方式; Dictionary.Add的实现使得它期望一对键/值对,并将一项添加到字典中。如果您需要添加多个项目,则需要多次调用Dictionary.Add-无法解决。

允许使用 的快捷方式是,仅获取任何2列Range中的值,然后将 that 转换成字典,而不是而不是随机选择两个大小相同或不相同的数组。

通过将第一列视为唯一键,将第二列视为值,使函数具有2D数组并将其转换为字典。

Public Function ToDictionary(ByVal keyValuePairs As Variant) As Scripting.Dictionary
    If Not IsArray(keyValuePairs) Then Err.Raise 5
    If GetDimensions(keyValuePairs) <> 2 Then Err.Raise 5 'see https://stackoverflow.com/q/6901991/1188513

    Dim result As Scripting.Dictionary
    Set result = New Scripting.Dictionary

    Const KEYCOL = 1, VALUECOL = 2

    Dim i As Long
    For i = LBound(keyValuePairs, KEYCOL) To UBound(keyValuePairs, KEYCOL)
        If result.Exists(keyValuePairs(i, KEYCOL)) Then Err.Raise 457
        result.Add Key:=keyValuePairs(i, KEYCOL), Item:=keyValuePairs(i, VALUECOL)
    Next

    Set ToDictionary = result
End Function

现在,您可以像这样将任何两列Range变成Dictionary

Dim things As Scripting.Dictionary
Set things = ToDictionary(Sheet1.Range("A2:B21").Value)

请注意,Range.Value在引用多个单元格时会生成基于1的2D Variant数组。