VBA字典

时间:2019-05-22 14:32:22

标签: excel vba

我正在尝试在VBA中创建key:value对的字典。密钥将是帐户ID,值应为整数列表。给定以下数据:

enter image description here

字典应如下所示:{'123':[3,5],'456':[4,7],'789':[6]}

在key:value对中用作值的数组将是动态的;我们不会事先知道会多大。我对如何在Python中执行此操作更加熟悉,但对VBA却不熟悉,VBA需要动态调整数组的大小。到目前为止,这是我的代码:

Sub test()
    Dim dict As New Scripting.Dictionary
    Dim sht As Worksheet
    Set sht = Sheets("Sheet1")
    Dim x As Integer
    Dim accountID As Variant
    Dim transaction As Variant

    For x = 2 To 5
        accountID = sht.Cells(x, 1).Value
        transaction = sht.Cells(x, 2).Value
        'Test whether the account exists in the dictionary
        'If the account does not exist, add it along with its transaction value
        If Not dict.Exists(accountID) Then
            Dim arr() As Variant
            arr(0) = transaction
            dict.Add accountID, arr
        'If the account exists, update its value array to include the transaction value
        ElseIf dict.Exists(accountID) Then
            arrLen = UBound(arr) - LBound(arr) + 1
            ReDim Preserve arr(arrLen + 1)
            dict(accountID)(arrLen + 1) = transaction
        End If
    Next x
End Sub

它在修改数组的部分上出错。应该如何改变?

1 个答案:

答案 0 :(得分:1)

作为项存储在字典中的数组不喜欢直接写入。您需要先将字典项写到临时数组,然后再将其设置回更新的数组。

var all = appWindow.GetElement(SearchCriteria.ByControlType(ControlType.ComboBox)
.AndByText(parentValue));
 var element = all.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, childValue));
                TextBox textBox = new TextBox(all, appWindow.ActionListener);

 TestStack.White.InputDevices.AttachedKeyboard keyboard = appWindow.Keyboard;
                textBox .Click();
                keyboard.Enter("test");

这可能是实现同一目标的更有效方法。这使用了几个技巧,分别使用Sub test() Dim dict As New Scripting.Dictionary Dim sht As Worksheet Dim x As Long Dim accountID As Variant, transaction As Variant Dim arr As Variant Set sht = Sheets("Sheet1") With sht For x = 2 To 6 ReDim arr(0) accountID = .Cells(x, 1).Value2 transaction = .Cells(x, 2).Value2 With dict If Not .Exists(accountID) Then ReDim arr(0) arr(0) = transaction .Add Key:=accountID, Item:=arr Else arr = .Item(accountID) ReDim Preserve arr(LBound(arr) To UBound(arr) + 1) arr(UBound(arr)) = transaction dict(accountID) = arr End If End With Next x End With ' Read back dictionary and array Dim k Dim dictStr As String dictStr = "{" For Each k In dict.Keys Debug.Print k, Join(dict(k), ", ") dictStr = dictStr & "'" & k & "':[" & Join(dict(k), ",") & "]," Next k dictStr = Left(dictStr, Len(dictStr) - 1) & "}" MsgBox dictStr End Sub Index对数组进行切片并过滤Filter数组

2D