daharon
daharon

Reputation: 2010

Select a Node in a TreeView with VBA

I have a TreeView within a UserForm in Excel. When a Node is selected from the TreeView, a ListBox is populated with data.
When an item in the ListBox is double-clicked, a separate UserForm is shown which allows the user do to stuff.
Once the user returns back to the TreeView UserForm, I want the Node that was selected previously to be highlighted.

The problem is that the UserForm basically resets itself, and I can't figure out how to select a Node with VBA.

I'm at the point where I'm debating on whether or not I can just manually fire a NodeClick event, as everything else I've tried has failed.

Any tips?

Upvotes: 5

Views: 25567

Answers (5)

Patrick O Reilly
Patrick O Reilly

Reputation: 63

Set xTree = Me!tv_bom.Object
        
xTree.Nodes.Item(Index).Selected = True

Upvotes: 0

Zdzisław Kes
Zdzisław Kes

Reputation: 31

In my Excel works:

TreeView1.Nodes(key).Selected = True

Upvotes: 3

Bas Verlaat
Bas Verlaat

Reputation: 852

Try this: objTreeview.Object.Nodes(KEY_NAME).Selected=TRUE

Where KEY_NAME is the key (string) that you used to create the node

Upvotes: 0

Arnold
Arnold

Reputation: 31

I know this is an old question but i had trouble enough finding a decent answer myself so here we go. Index or Key's are not always available. On create I place the fullpath of the node in the node.tag. On double-click I recall the tag value, later on I search the treeview node collection for the tag. To much? not efficient? maybe but its works likes a charm every time and i can use my own identifiers in the tag based on the purpose of the treeview. The find code:

Sub MyTreeview_FindNode(strKey As String)
Dim myNode As Node

   For Each myNode In Me.Treeview.Nodes
       If myNode.Tag = strKey Then
          myNode.Selected = True
          myNode.EnsureVisible
          End If
       Next
End Sub 

Upvotes: 3

Ryan
Ryan

Reputation: 8005

You have several options. First, when the TreeView UserForm displays the second UserForm, you either need to:

  1. Save the ID of the selected node (use a form-level or module-level variable). Then you need to write a method to select the node upon return to the form. IIRC, you need to have a unique 'Key' or ID for each node element and then use TreeView.Select for the node returned from TreeView.FindNode. -- or --
  2. Hide the TreeView UserForm instead of closing it (Me.Hide). When the second UserForm is closed (or OK/Cancel pressed), then show the TreeView UserForm again (TreeViewForm.Show).

Upvotes: 1

Related Questions