Option Explicit
Private Sub Command1_Click() CopyTreeview TreeView1, TreeView2 End Sub '_________________________________________________________ Private Sub CopyTreeview(objTVSrc As TreeView, objTVDest As TreeView) 'Copies the source treeview to a destination 'treeview. Assumes that both treeviews use the 'same (or identical) Imagelists. Dim nodeRoot As Node objTVDest.Nodes.Clear For Each nodeRoot In objTVSrc.Nodes If (nodeRoot.Parent Is Nothing) Then Call CopyTVParentNode(nodeRoot, objTVDest.Nodes) End If Next End Sub '_________________________________________________________ Private Sub CopyTVParentNode(nodeParent As Node, nodesDest As Nodes) 'Walks the specified source parent treeview node, 'and all of it's children nodes, adding them to the 'specified destination Nodes collection. ' 'nodeParent: parent node to walk and copy from 'nodesDest : destination Nodes collection to copy to Dim nodeDummy As Node Dim nodeChild As Node 'First add the parent node to the destination nodes collection. Set nodeDummy = CopyNode(nodeParent, nodesDest) 'Get the current parent node's first child Set nodeChild = nodeParent.Child 'Now walk through the current parent node's children 'appending the current child node's text to the passed string Do While Not (nodeChild Is Nothing) 'If the current child node has it's own children... If nodeChild.Children Then 'Recursively call this proc copying all of it's children '(it becomes the new parent node) Call CopyTVParentNode(nodeChild, nodesDest) Else 'Add the child node to the destination nodes collection. Set nodeDummy = CopyNode(nodeChild, nodesDest) End If 'Get the current child node's next sibling Set nodeChild = nodeChild.Next Loop End Sub '_________________________________________________________ Private Function CopyNode(nodeSrc As Node, nodesDest As Nodes) As Node With nodeSrc If (.Parent Is Nothing) Then 'Root node Set CopyNode = nodesDest.Add(, , _ .Key, .Text, _ .Image, .SelectedImage) CopyNode.Expanded = True Else 'Child node Set CopyNode = nodesDest.Add(.Parent.Index, _ tvwChild, _ .Key, .Text, _ .Image, .SelectedImage) CopyNode.Expanded = True End If End With End Function |