|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 chxw68 于 2013-11-28 08:53 编辑
此问题是网友GovanWAng提出来的,要求建立乡、村、组、村民四级目录树,试着用其他方法做比较烦琐,后来改用字典嵌套的方法,很好的解决了问题,发现程序层次清晰、结构严谨,希望能够抛砖引玉,对大家有所帮助。
Private Sub UserForm_Initialize() '使用此段程序,必须在VBE中先加载"Micerosoft TreeView Conntrol,version6.0"控件。
Dim d As New Dictionary '建立字典
Dim i, j, r, c As Integer
Dim ws As Worksheet
Dim nodex As Node
With TreeView1 '设置TreeView控件属性
.Nodes.Clear
.Style = 6
.LineStyle = 1
End With
Set ws = Worksheets("sheet1")
r = Cells(Rows.Count, 1).End(xlUp).Row
arr = Range("a2:d" & r)
n = 0
For i = 1 To UBound(arr)
If Not d.Exists(arr(i, 1)) Then
Set d(arr(i, 1)) = CreateObject("scripting.dictionary") '一级字典嵌套
End If
If Not d(arr(i, 1)).Exists(arr(i, 2)) Then
Set d(arr(i, 1))(arr(i, 2)) = CreateObject("scripting.dictionary") '二级字典嵌套
End If
If Not d(arr(i, 1))(arr(i, 2)).Exists(arr(i, 3)) Then
Set d(arr(i, 1))(arr(i, 2))(arr(i, 3)) = CreateObject("scripting.dictionary") '三级字典嵌套
End If
If Not d(arr(i, 1))(arr(i, 2))(arr(i, 3)).Exists((arr(i, 4))) Then
Set d(arr(i, 1))(arr(i, 2))(arr(i, 3))(arr(i, 4)) = CreateObject("scripting.dictionary") '四级字典嵌套
End If
Next
TreeView1.Nodes.Clear
Set nodex = TreeView1.Nodes.Add(, , "乡镇", "乡镇") '添加根节点
For Each aa In d.Keys ‘在一级关键字中集合中循环
i = i + 1
Set nodex = TreeView1.Nodes.Add("乡镇", tvwChild, aa & i, aa) '添加二级节点
For Each bb In d(aa).Keys ‘在二级关键字集合中循环
j = j + 1
Set nodex = TreeView1.Nodes.Add(aa & i, tvwChild, bb & j, bb) '添加三级节点
For Each cc In d(aa)(bb).Keys ‘在字典关键字集合中循环
k = k + 1
Set nodex = TreeView1.Nodes.Add(bb & j, tvwChild, cc & k, cc) '添加四级节点
For Each dd In d(aa)(bb)(cc).Keys ‘在l字典关键字集合中循环
l = l + 1
Set nodex = TreeView1.Nodes.Add(cc & k, tvwChild, dd & l, dd) '添加五级节点
Next
Next
Next
Next
End Sub |
评分
-
22
查看全部评分
-
|