【问题标题】:How to add dictionary values to an Array in VBA instead of reference如何将字典值添加到 VBA 中的数组而不是引用
【发布时间】:2018-08-29 06:12:33
【问题描述】:

我通过 JSON 将数据从 Excel 发送到 dashing.io 仪表板。 我发送的数据由几组数据组成,例如

[{"Group":"Interface","progress";"10"},{"Group":"HMI","progress";"20"}]

现在我正在使用几个字典对象 progress1、progress2 来保存数据,例如:

DIM progress1 as new Dictionary
DIM progress2 as new Dictionary
progress1.add "Group", "Interface"
progress1.add "Progress", 10
progress2.add "Group", "HMI"
progress2.add "Progress", 20

最后为了创建 JSON 对象,将两个进度字典添加到一个对象中:

Dim body as new Dictionary
body.add Array(progress1, progress2)

由于进度项不止两个,我想创建一个 for 循环来将数据添加到字典中,然后将该字典项添加到类似数组中

for i=1 to 10
  progress.add "Group", Range(i,1)
  progress.add "progress", Range (i,2)
next i
overall_progress.add (progress)

似乎我将对象添加为引用,而不是对象的值。如果循环运行 10 次,我最终会得到十次相同的条目。

知道如何将字典的值添加到数组中,而不是引用吗?

【问题讨论】:

    标签: arrays excel vba dictionary


    【解决方案1】:

    如果使用“工厂”函数,则在循环中创建对象更容易管理。

    例如:

    Sub Tester()
    
        Dim body As New Collection, i As Long
    
        For i = 1 To 10
            body.Add Progress(Cells(i, 1), Cells(i, 2))
        Next i
    
    End Sub
    
    Function Progress(grp, prog) As Object
        Dim rv As New scripting.dictionary
        rv.Add "Group", grp
        rv.Add "Progress", prog
        Set Progress = rv
    End Function
    

    【讨论】:

    • 哇,太好了!我不得不使用“Dim rv as New Dictionary”,但除此之外,它现在效果很好。非常感谢!
    猜你喜欢
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多