' 用户窗体代码(假设窗体名为UserForm1,TreeView控件名为TreeView1)
' 需要引用Microsoft Windows Common Controls 6.0 (SP6)
Private Sub UserForm_Initialize()
InitTreeView
End Sub
Sub InitTreeView()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1") ' 根据实际工作表名称修改
TreeView1.Nodes.Clear
' 获取根节点
Dim rootCell As Range
Set rootCell = ws.Range("A1")
If rootCell.Value = "" Then
MsgBox "根目录未找到!", vbCritical
Exit Sub
End If
' 添加根节点
Dim rootKey As String
rootKey = "RootNode"
TreeView1.Nodes.Add , , rootKey, rootCell.Value
TreeView1.Nodes(1).Expanded = True
' 初始化层级字典
Dim parentNodes As Object
Set parentNodes = CreateObject("Scripting.Dictionary")
parentNodes.Add 0, TreeView1.Nodes(1) ' 根节点的层级为0
' 获取数据区域的最后一行和最后一列
Dim lastRow As Long
Dim lastCol As Long
lastRow = GetLastRow(ws)
lastCol = GetLastCol(ws)
' 遍历数据行
Dim i As Long
Dim j As Long
For i = 2 To lastRow
Dim currentLevel As Long
currentLevel = 0
' 遍历列,从第二列开始到最后一列
For j = 2 To lastCol
Dim cellVal As String
cellVal = Trim(ws.Cells(i, j).Value)
' 如果单元格为空,跳过当前列,继续遍历下一列
If cellVal = "" Then
currentLevel = j - 1 ' 更新当前层级
GoTo ContinueLoop ' 跳过当前迭代
End If
currentLevel = j - 1 ' 当前层级(从0开始)
' 确保父节点存在
If Not parentNodes.Exists(currentLevel - 1) Then
MsgBox "层级错误:行" & i & " 列" & j, vbCritical
Exit Sub
End If
' 创建唯一键并添加节点
Dim nodeKey As String
Dim newNode As Node
nodeKey = "R" & i & "C" & j
Set newNode = TreeView1.Nodes.Add(parentNodes(currentLevel - 1), tvwChild, nodeKey, cellVal)
' 更新层级字典
If parentNodes.Exists(currentLevel) Then parentNodes.Remove currentLevel
parentNodes.Add currentLevel, newNode
ContinueLoop:
Next j
' 清理层级字典,确保下一行的层级从正确的位置开始
Dim keys As Variant
Dim k As Variant
keys = parentNodes.keys
For Each k In keys
If k > currentLevel Then parentNodes.Remove k
Next k
Next i
End Sub
' 获取数据区域的最后一行
Function GetLastRow(ws As Worksheet) As Long
Dim lastRow As Long
Dim col As Long
Dim tempLastRow As Long
lastRow = 0
For col = 1 To ws.Columns.Count
tempLastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).row
If tempLastRow > lastRow Then
lastRow = tempLastRow
End If
Next col
GetLastRow = lastRow