在VBA中递归打印下一个词典

时间:2014-09-18 09:48:27

标签: excel vba recursion dictionary data-structures

我想在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

1 个答案:

答案 0 :(得分:2)

我实际上会提出一种不同的方式来显示结果。我认为这更符合逻辑,但欢迎您根据自己的具体需求进行修改。就像提示打印节点的逻辑树一样,如下所示,然后在需要时操作结果。

所以这个树看起来像这样(注意我添加了一个深度级别

dictionary tree

和重现的代码

Private i As Long
Private depth As Long

Sub Main()
Cells.ClearContents

    Dim dict As New Dictionary
    Dim subDict As New Dictionary
    Dim lvlDict As New Dictionary

    lvlDict.Add "LVL KEY", "LVL ITEM"

    subDict.Add "HELLO", ":)"
    subDict.Add "WORLD", ":("
    subDict.Add "OTHER", lvlDict

    dict.Add "FOO", "BAR"
    dict.Add "BOO", subDict

    i = 1
    depth = 0
    TraverseDictionary dict

    Columns.AutoFit

End Sub

Private Sub TraverseDictionary(d As Dictionary)

    For Each Key In d.Keys
        Range("A" & i).Offset(0, depth) = "KEY: " & Key
        If VarType(d(Key)) = 9 Then
            depth = depth + 1
            TraverseDictionary d(Key)
        Else
            Range("B" & i).Offset(0, depth) = "ITEM: " & d(Key)
        End If
        i = i + 1
    Next
End Sub

和电子表格结果:

enter image description here


要获取变量类型或其类型名称,您可以使用:

Debug.Print TypeName(dict("HELLO")), VarType(dict("HELLO"))