【发布时间】:2014-11-12 14:26:08
【问题描述】:
我想在 VBA 中打印嵌套字典。基本上我有一个Dictionary,其中每个键都是String,但每个值可以是String 或另一个Dictionary。
说我的Dictionary 获得了价值
{ "FOO" => "BAR" , "HELLO" => { "WORLD => ":)", "OTHER" => ":(" } }
我想在 Excel 电子表格中显示:
FOO |BAR |
HELLO|WORLD|:)
HELLO|OTHER|:(
我的问题是我需要找到一种方法来猜测每个键下的值的类型,所以当我调用dict("HELLO") 时,我可以显示该值是字符串还是字典调用再次相同的功能。
为此,我需要知道:
- 如果有办法知道字典中存储的值的类型是什么
- 如果有办法将该值转换为目标类型(字符串或字典)
这就是我尝试过的方法
Function display_dictionary(dict As Scripting.Dictionary, out As Range) As Integer
Dim vkey As Variant
Dim key As String
Dim row_offset As Integer
Dim value As Object
Dim svalue As String
Dim dvalue As Dictionary
Dim each_offset As Integer
row_offset = 0
For Each vkey In dict.Keys()
key = vkey
Set value = dict(key)
if value is String then
svalue = ???
out.offset(row_offset, 0).value = key
out.offset(row_offset, 1).value = svalue
row_offset = row_offset + 1
else if value is Dictionary
dvalue = ???
each_offset = display_dictionary(dvalue, out.offset(row_offset, 1))
For each_row = 0 To each_offset - 1
out.offset(row_offset + each_row) = key
Next
row_offset = row_offset + each_offset
End If
Next
End
【问题讨论】:
标签: excel vba recursion dictionary data-structures