Trying to copy the text of selected treeview nodes to clipboard but only getting the last node in clipboard

Viewed 303

I am using excel/vba to create a tree structure. Nodes have checkbox in front of them. I am using a recursive function to traverse the nodes and copy the text of selected/checked nodes. I tried to put it in variable, excel rows, arrays but I am only getting last selected node's text.

Below is the recursive function.

I am passing the root node to it. How to copy selected items?

Public Sub TraverseTree(objNode As Node)

    Dim objSiblingNode As Node
    Set objSiblingNode = objNode
    
   Do
        If objSiblingNode.Checked Then
        Debug.Print objSiblingNode.Text
        End If
        If Not objSiblingNode.Child Is Nothing Then
            Call TraverseTree(objSiblingNode.Child)
        End If
        Set objSiblingNode = objSiblingNode.Next
   Loop While Not objSiblingNode Is Nothing
   
End Sub

Tree nodes defined in VBA code

'Parent Nodes

TreeView1.Nodes.Add Key:="P1", Text:="Phone is down/blank screen"
TreeView1.Nodes.Add Key:="P2", Text:="phone is showing Configuring IP"
TreeView1.Nodes.Add Key:="P3", Text:="Phone stuck at registering"

'Child for P1

TreeView1.Nodes.Add "P1", tvwChild, "ch1", "Is the phone getting power?"

'Child for ch1

TreeView1.Nodes.Add "ch1", tvwChild, "ch1.1", "Yes"
TreeView1.Nodes.Add "ch1", tvwChild, "ch1.2", "No"

'Child for ch1.1

TreeView1.Nodes.Add "ch1.1", tvwChild, "ch1.1.1", "Do you see any buttons lit up, what are they?"

enter image description here

1 Answers

So, try the next scenario, please:

  1. Declare a Private Variable on top of form module (in the declarations area):
    Private strWiew As String
  1. Your TraverseTree Sub will become:
Private Sub TraverseTree(objNode As Node)
   Do
        If objNode.Checked Then
            If strWiew = "" Then
               strWiew = objNode.Text
            Else
               strWiew = strWiew & vbCrLf & vbTab & objNode.Text
            End If
        End If
        If Not objNode.Child Is Nothing Then
            Call TraverseTree(objNode.Child)
        End If
        Set objNode = objNode.Next
   Loop While Not objNode Is Nothing
End Sub
  1. You need the function to put the resulted string in clipboard:
    Dim clipboard As New MSForms.DataObject

    clipboard.SetText strNode
    clipboard.PutInClipboard
End Sub
  1. Your Copy button Click event will become:
    Private Sub CommandButton1_Click()
     Dim objNode As Node
        
     Set objNode = TreeView1.Nodes("P1")
     strWiew = ""
     TraverseTree objNode
     CopyToClipboard strWiew
    End Sub
  1. Run your application. Check the tree node you want their text to be returned and press Copy button. Open Notepad, Wordpad, Word (any text editor) and try Ctrl + V...
Related