【问题标题】:Insert multiple dictionaries in an array by using a loop使用循环在数组中插入多个字典
【发布时间】:2018-08-24 05:20:07
【问题描述】:

我在使用循环填充 excel vba 中的数组时遇到了问题。 其实我想用以下方式填写字典myitemprodukt1produkt2 可能都是字典。

myitem("productionOrderItems")=Array(produkt1, produkt2).

因为我现在不知道我有多少次produkt,所以我使用循环来创建字典produkt。 每次创建和填充字典 produkt 时,我都想将其分配给 Array,就像我上面描述的那样。 以下代码显示了创建字典的循环。但在那种情况下,显然只创建了最后一个字典 (i=counter)。 counter 是我想分配给Array 的产品数量。

myitem As New Dictionary

For i = 1 To counter
    Dim produkt As New Dictionary
    zeile = 2 + i
    produkt("id") = Tabelle6.Cells(zeile, 1).Value
    Tabelle6.Cells(zeile, 1).Value = ""
    produkt("actualWithdrawalQuantity") = Tabelle6.Cells(zeile, 2).Value
    Tabelle6.Cells(zeile, 2).Value = ""
    produkt("articleId") = Tabelle6.Cells(zeile, 3).Value
    Tabelle6.Cells(zeile, 3).Value = ""
    produkt("articleNumber") = Tabelle6.Cells(zeile, 4).Value
    Tabelle6.Cells(zeile, 4).Value = ""
    produkt("createdDate") = Tabelle6.Cells(zeile, 5).Value
    Tabelle6.Cells(zeile, 5).Value = ""
    produkt("positionNumber") = Tabelle6.Cells(zeile, 6).Value
    Tabelle6.Cells(zeile, 6).Value = ""
    produkt("quantity") = Tabelle6.Cells(zeile, 7).Value
    Tabelle6.Cells(zeile, 7).Value = ""
    produkt("targetWithdrawalDate") = Tabelle6.Cells(zeile, 8).Value
    Tabelle6.Cells(zeile, 8).Value = ""
    produkt("targetWithdrawalQuantity") = Tabelle6.Cells(zeile, 9).Value
    Tabelle6.Cells(zeile, 9).Value = ""
    myitem("productionOrderItems") = Array(produkt)
Next

也许有人知道如何解决这个问题。 提前致谢!

【问题讨论】:

    标签: arrays excel vba dictionary for-loop


    【解决方案1】:

    问题是

    myitem("productionOrderItems") = Array(produkt)
    

    总是用新数组覆盖myitem("productionOrderItems"),而不保留旧数组。所以最后只有最后一个“新”数组。

    您需要做的是每次将现有数组扩展一个条目:

    Dim tmpArr As Variant
    tmpArr = myitem("productionOrderItems") 'read existing array into temp array
    If IsEmpty(tmpArr) Then
        tmpArr = Array(produkt) 'first time we need to generate a array
    Else 'for all other times we need to append to the existing array
        ReDim Preserve tmpArr(UBound(tmpArr) + 1) 'resize existing array by one
        Set tmpArr(UBound(tmpArr)) = produkt 'add the product to the newly added array entry
    End If
    myitem("productionOrderItems") = tmpArr 'write temp array back to dictionary
    

    【讨论】:

    • 我正在使用数组来设置 PUT 请求。完成请求后,会出现错误“productionorderItems:duplicate id”。我想知道数组是否包含重复的 id。但为此,我必须显示一个显示 produkt 数组的 MsgBox。你能告诉我怎么做吗?或者您知道为什么会出现重复 id 的错误吗?
    • 您需要一个循环来输出数组或字典的所有项目:How to monitor the values in a Dictionary in the Excel VBA watch window?。如果我的回答是您原始问题的解决方案,请考虑将其标记为解决方案。
    【解决方案2】:

    我发现了问题所在: 循环有效,但“produkt”字典尚未被覆盖,因此已插入两次相同的“produkt”。 我通过在循环开始时将 produkt 设置为空来规避该问题。 感谢您的帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-11
      • 2015-03-16
      • 2020-03-04
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多