数据图如所示
首先找到我们的TreeView控件插入
然后键入如下代码
Private Sub UserForm_Initialize()
Dim i As Integer
Dim j As Integer
Dim arr
arr = Sheet3.Range("b3").CurrentRegion
With Me.TreeView1
.Style = tvwTreelinesPlusMinusPictureText
.LineStyle = tvwRootLines
.CheckBoxes = False
With .Nodes
.Clear
.Add Key:="科目", Text:="科目名称"
For i = 1 To UBound(arr, 2)
For j = 2 To UBound(arr, 1) - 1
If Not IsEmpty(arr(j, i)) Then
If i = 1 Then
.Add relative:="科目", _
relationship:=tvwChild, _
Key:=arr(j, i), _
Text:=arr(j, i)
ElseIf Not IsEmpty(arr(j, i - 1)) Then
.Add relative:=arr(j, i - 1), _
relationship:=tvwChild, _
Key:=arr(j, i), _
Text:=arr(j, i)
Else
.Add relative:=CStr(Sheet3.Cells(j + 2, i).End(xlUp)), _
relationship:=tvwChild, _
Key:=arr(j, i), _
Text:=arr(j, i)
End If
End If
Next
Next
End With
End With
End Sub
最后效果如图所示
再加上一个双击可以将所选末级科目输入单元格的事件
Private Sub TreeView1_DblClick()
Dim Lsr As Long
With Sheet3
Lsr = .Cells(Rows.Count, "G").End(3).Row + 1
If Me.TreeView1.SelectedItem.Children = 0 Then
.Cells(Lsr, "G") = Me.TreeView1.SelectedItem.Text
Else
MsgBox "你选择的不是末级科目!"
End If
End With
End Sub