|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 larer 于 2019-4-5 18:32 编辑
平时用VBA编程时,经常需要利用字典统计和保存各种信息,但是,当数据量较大,字典嵌套,或数据结构复杂时,在VBE中要查看字典的内容就非常地不方便.
所以,我写了一个函数,可以把字典的内容显示到一个新的工作中表,可以直观地看到字典的内容,方便程序的调试.该函数采用递归法,可以显示任意多级别嵌套的字典,分享出来,方便各位编友,希望大家热情指正!
- '递归法实现字典解析,解决VBE环境中调试字典不便的问题
- '作者:larer QQ:1302230383
- '参数说明:
- 'ByRef dic As Variant 需要解析的字典变量
- 'Optional DebugWS As Worksheet 仅供程序内部递归时指定,人工调用函数时不用指定该参数
- 'Optional CellAddr 仅供程序内部递归时指定,人工调用函数时不用指定该参数
- 'Optional ByRef OffsetLine As Long = 0 仅供程序内部递归时指定,人工调用函数时不用指定该参数
- Function Debug_DisplayForDictionary(ByRef dic As Variant, Optional DebugWS As Worksheet, Optional CellAddr$, Optional ByRef OffsetLine As Long = 0)
- Dim i&
- Dim arr, brr
- Dim ActiveWs, FirstRun As Boolean
-
- If TypeName(dic) <> "Dictionary" Then Exit Function
- If CellAddr = "" Then
- With ThisWorkbook
- .Activate
- FirstRun = True
- Set ActiveWs = ActiveSheet
- For i = 1 To .Worksheets.Count
- If .Worksheets(i).Name = "Debug_DisplayForDictionary" Then Exit For
- Next
- If i > .Worksheets.Count Then
- .Worksheets.Add after:=.Sheets(.Sheets.Count)
- Set DebugWS = ActiveSheet
- With DebugWS
- CellAddr = .Cells(1, 1).Address
- .Name = "Debug_DisplayForDictionary"
- .Cells.ClearContents
- End With
- Else
- Set DebugWS = .Worksheets(i)
- With DebugWS
- CellAddr = .Cells(1, 1).Address
- .Cells.ClearContents
- End With
- End If
- End With
- End If
- With DebugWS.Range(CellAddr)
- arr = dic.keys
- brr = dic.items
- For i = 0 To UBound(arr)
- .Offset(OffsetLine, 0).Value = arr(i)
- Select Case TypeName(brr(i))
- Case "Boolean", "Byte", "Integer", "Long", "Single", "Double", "Currency", "Decimal", "Date", "String"
- .Offset(OffsetLine, 1).Value = brr(i)
- OffsetLine = OffsetLine + 1
- Case "Range"
- .Offset(OffsetLine, 1).Value = "[" & brr(i).Address & "]"
- OffsetLine = OffsetLine + 1
- Case "Dictionary"
- Call Debug_DisplayForDictionary(brr(i), DebugWS, .Offset(0, 1).Address, OffsetLine)
- Case Else
- .Offset(OffsetLine, 1).Value = "(" & TypeName(brr(i)) & ")"
- OffsetLine = OffsetLine + 1
- End Select
- Next
- End With
-
- If FirstRun Then
- ActiveWs.Activate
- End If
- End Function
复制代码 '调用示例:
- Sub Example()
- Dim dic
-
- Set dic = createobject("scripting.dictionary")
- dic("张三") = "总经理"
- Set dic("李四") = createobject("scripting.dictionary")
- dic("李四")("性别") = "男"
- dic("李四")("生日") = "1980/1/1"
- dic("李四")("职务") = "采购员"
- Set dic("李四")("亲属") = createobject("scripting.dictionary")
- Set dic("李四")("亲属")("妻子") = createobject("scripting.dictionary")
- dic("李四")("亲属")("妻子")("工作单位") = "图书馆"
- Set dic("李四")("亲属")("妻子")("亲属") = createobject("scripting.dictionary")
- dic("李四")("亲属")("妻子")("亲属")("弟弟") = "张磊"
- dic("李四")("亲属")("妻子")("亲属")("哥哥") = "张三"
- dic("李四")("亲属")("儿子") = "小明"
- Debug_DisplayForDictionary dic '此句为调用函数解析字典
- End Sub
复制代码 程序运行结果是,在当前工作薄中自动建立了一个名为"Debug_DisplayForDictionary"工作表,并在工作表中显示该字典的内容.
|
评分
-
7
查看全部评分
-
|