Excel VBA solution to identify expanded Nodes in a UserForm TreeView

I have a TreeView control (Treeview1) displayed in excel.UserForm using classic vba.

I wish to return the oNode.text values of those TreeView nodes that are Expanded (not collapsed)
Do I have to detect each node 'expansion' event as it occurs and, for each, write TreeView1.SelectedItem.key to a worksheet,
Could I enumerate the TreeView as follows?

dim oNode as Node
for each oNode in Treeview1.NodeS
      ... and return to my worksheet the node.key value of each node that is expanded?

Who is Participating?
Martin LissConnect With a Mentor Older than dirtCommented:
You can't use For Each with a Treeview.

Private Sub Command1_Click()
Dim lngNode As Integer

For lngNode = 1 To Treeview1.Nodes.Count
    If Treeview1.Nodes(lngNode).Expanded Then
    ' Write to worksheet here
        'MsgBox Treeview1.Nodes(lngNode).Key
    End If
End Sub

Open in new window

Kelvin4Author Commented:
Many thanks!
Martin LissOlder than dirtCommented:
You’re welcome and I’m glad I was able to help.

If you expand the “Full Biography” section of my profile you’ll find links to some articles I’ve written that may interest you.

Marty - Microsoft MVP 2009 to 2017
              Experts Exchange Most Valuable Expert (MVE) 2015, 2017
              Experts Exchange Top Expert Visual Basic Classic 2012 to 2017
              Experts Exchange Top Expert VBA (current)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.