Private Sub btnLoadTreeView_Click()
'// This is used to save a reference to the Parent node
Dim nP As Node
'// General range
Dim c As Excel.Range
'// Note - must include the $'s as cell address is compared to this
Const cROOT As String = "$B$4"
'// Will handle most common errors in-line
On Error Resume Next
With TreeView1
'// Clear any existing
.Nodes.Clear
'// Add the Root node. All nodes also have a key set. The .TEXT property is set
'// to the contents of the cell. The .KEY property is the Cell address.
'// Keys must be unique - so not using the cell contents for the key
Set np = .Nodes.Add(, , Range(cROOT).Address, Sheet1.Range(cROOT).Value)
'// Loop through all cells in the Root Cell currentRegion. This should/will
'// include all defined cells as long as the general schema is adhered to
'// with no totally blank rows or columns
For Each c In Sheet1.Range(cROOT).CurrentRegion
'// Cell contains sometihng and is not the ROOT cell?
If c.Value <> vbNullString And c.Address <> cROOT Then
'// Find the parent node for this cell. This is the cell
'// 1 column to the left and .END(xlup) upwards...
Set nP = .Nodes(c.Offset(, -1).End(xlUp).Address)
'// Snags - The parent should exist so schema is wrong
If nP Is Nothing Then
MsgBox "ERROR: Parent node " & c.Offset(, -1).End(xlUp).Value & " not found...", vbExclamation, "Error"
Exit Sub
End If
'// simply add a new child to the parent - .TEXT and .KEY from the cell
'// text is the cell Value, Key is the Cell Address
.Nodes.Add nP, tvwChild, c.Address, c.Value
'// check added OK
If Err.Number <> 0 Then
MsgBox "ERROR: The node " & c.Value & " is a duplicate. All node descrptions must be unique", vbExclamation, "Error"
Exit Sub
End If
'// Expand the parent just so the new node is visible
nP.Expanded = True
End If
Next
'// Select and show the ROOT node
With .Nodes(Range(cROOT).Address)
.Selected = True
.EnsureVisible
End With
End With
'// All done
Exit Sub
End Sub
NOTE: - Your schema is incorrect. Cell A21 (The cell contents, not the Address) should be offset one row down - not directly opposite its parent, AA2 - All the others cells in the schema follow that convention. This causes AA21 to be a child of AA1 instead of AA2.
Bookmarks