Parent Nodes
To add the parent nodes to our TreeView, we'll use the Initialize
event of the User Form.
From the dropdown boxes at the top of the coding editor, then, select the UserForm item:
This will give you a click event, which you don't want. We need the Initialize
event. From the dropdown on the right, select Initialize:
An Initialize event will be added to your coding window. You can delete the Click event, as you won't need it.
The first thing we can do in the Initialize event is to activate Sheet1. This is the sheet with all the TreeView data. If we don't make Sheet1 the active sheet then Treeview will try to pull its data from Sheet2, if that sheet is displayed in Excel.
The code is only one line. This:
Worksheets("Sheet1").Activate
In between the round brackets of Worksheets, you can type the name of worksheet in between quote marks.
The next five lines get the parent nodes for the TreeView. Add the following:
Treeview1.Nodes.Add Key:=Sheet1.Cells(1, 1).Value, Text:=Sheet1.Cells(1, 1).Value
Treeview1.Nodes.Add Key:=Sheet1.Cells(1, 2).Value, Text:=Sheet1.Cells(1, 2).Value
Treeview1.Nodes.Add Key:=Sheet1.Cells(1, 3).Value, Text:=Sheet1.Cells(1, 3).Value
Treeview1.Nodes.Add Key:=Sheet1.Cells(1, 4).Value, Text:=Sheet1.Cells(1, 4).Value
Treeview1.Nodes.Add Key:=Sheet1.Cells(1, 5).Value, Text:=Sheet1.Cells(1, 5).Value
Your coding window should look like this:
Press F5 to run your form. You should find that the TreeView looks like this:
We now have five parent nodes on our TreeView. These parent nodes don't have any child nodes, yet, however.