简体   繁体   English

遍历 VBA 字典?

[英]Iterate over VBA Dictionaries?

I'm using the Dictionary class in the MS Runtime Scripting library to store where labels are going to go for a report template.我正在使用 MS 运行时脚本库中的字典 class 来存储标签将转到 go 的位置以获取报告模板。 Is there a way to iterate over all the key value pairs in that dictionary like in Python?有没有办法像 Python 那样遍历该字典中的所有键值对?

I just want to use the key as the row number (It's all going in column A) and the value will be the label header.我只想使用键作为行号(全部在 A 列中),值将是 label header。

Something like:就像是:

For Each key in dict
    Range("A" & key).Value = dict(key)
Next key

Try:尝试:

For Each varKey In oDic.Keys()
    Range("A" & varKey).Value = oDic(varKey)
Next

Note that the key iterator must be declared as a Variant .请注意,键迭代器必须声明为Variant

Not a lot out there for this but, if you have multiple values per key, such as in an array, you'll need a bit more code.这方面的内容不多,但是,如果每个键有多个值,例如在数组中,您将需要更多代码。 This is my first time responding to a post here so apologies if I'm doing something wrong...这是我第一次在这里回复帖子,如果我做错了什么,我深表歉意......

    Dim dict As New Scripting.Dictionary
    Dim k As Variant
    Dim v As Variant

    Set dict = New Scripting.Dictionary
    'Add code to populate your dictionary

    For Each k In dict.Keys()
        Debug.Print k, Join(dict(k), ",") 'Prints out all the details for the key
        For Each v In dict(k)
            Debug.Print v
        Next
    Next k

Part of this code comes from this post: VBA Dictionary with Dynamic Arrays部分代码来自这篇文章: VBA Dictionary with Dynamic Arrays

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM