PDA

View Full Version : TreeView, selected element and all below



lenrok
08-04-2011, 07:21 AM
Hi everyone.
I have this code, but instead of "all childred" I would like to have : element which has been selected and all below elements.
So my question is how to change this code?



Option Explicit

Dim strNodeNames As String, iCount As Integer

Private Sub UserForm_Initialize()
Dim xlWks As Excel.Worksheet
Dim i As Long, j As Integer
Dim strText As String
Dim iCell As Integer
Dim strNodKey As String, strParentNodKey As String

Set xlWks = ThisWorkbook.Worksheets(1)

With Me.TreeView1
.Nodes.Clear
On Error Resume Next

Do
i = i + 1
Do
j = j + 1
strText = xlWks.Cells(i, j)
If Len(strText) > 0 Then
If j = 1 Then
.Nodes.Add Key:=strText, _
Text:=strText
Else
With xlWks
For iCell = 1 To j
strNodKey = strNodKey & .Cells(i, iCell).Value
Next
End With
strParentNodKey = Left(strNodKey, Len(strNodKey) - Len(strText))

.Nodes.Add relative:=strParentNodKey, _
relationship:=tvwChild, _
Key:=strNodKey, _
Text:=strText

strNodKey = vbNullString
strParentNodKey = vbNullString
End If
Else
j = 0: Exit Do
End If
Loop
If Len(xlWks.Cells(i, 1)) = 0 Then Exit Do
Loop

On Error GoTo 0

End With

End Sub

Private Sub TreeView1_NodeClick(ByVal Node As MSComctlLib.Node)
strNodeNames = vbNullString
ReadNodesChildrenText Node
Me.Label1.Caption = strNodeNames

iCount = 1
HasParent Node
Me.Label2.Caption = iCount
End Sub

Sub ReadNodesChildrenText(ByVal Node As MSComctlLib.Node)
Dim lngChildren As Long, i As Long
Dim objNode As MSComctlLib.Node

lngChildren = Node.Children
If lngChildren > 0 Then
Set objNode = Node.Child.FirstSibling

For i = 1 To lngChildren
If objNode.Children = 0 Then
strNodeNames = strNodeNames & objNode.Text & ", "
Else
ReadNodesChildrenText objNode
End If
Set objNode = objNode.Next
Next
End If
End Sub

Sub HasParent(ByVal Node As MSComctlLib.Node)
Dim objNode As MSComctlLib.Node

On Error Resume Next
Set objNode = Node.Parent
On Error GoTo 0
If Not objNode Is Nothing Then
iCount = iCount + 1
HasParent objNode
End If

End Sub