recursion地打印VBA中的下一个字典

我想在VBA中打印嵌套字典。 基本上我有一个Dictionary ,其中每个键是一个String ,但每个值可以是一个String或另一个Dictionary

说我的Dictionary已经有了价值

{ "FOO" => "BAR" , "HELLO" => { "WORLD => ":)", "OTHER" => ":(" } }

我想在Excel电子表格中显示:

 FOO |BAR | HELLO|WORLD|:) HELLO|OTHER|:( 

我的问题是,我需要find一种方法来猜测每个键下的值是什么types,所以当我调用dict("HELLO")我可以显示值,如果它是一个string或如果它是一个字典调用同样的function。

为了做到这一点,我需要知道:

  • 如果有一种方法可以知道字典中存储的值的types是什么
  • 如果有方法将该值转换为目标types(string或字典)

所以这是我所尝试的

 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 

我实际上会提出一些不同的方式来显示结果。 我认为这更合乎逻辑,但欢迎您修改它以适应您的特定需求。 就像提示打印节点的逻辑树一样,如下所示,然后在需要时操作结果。

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

字典树

和代码重现

 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 

和电子表格结果:

在这里输入图像描述


要获得variablestypes或其types名称,可以使用这个:

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