Автоматический выбор / отмена выбора родительских флажков Treeview Excel-VBA.
У меня есть код из следующих источников:
https://www.planet -source-code.com / vb / scripts / ShowCode.asp? TxtCodeId = 48560 & lngWId = 1
http://www.vbforums.com/showthread.php?249131-VB-Check-All-Treeview-Children
Принимая Treeview как Treeview1, я объединил их обоих и сделал свой код.
Private Sub TreeView1_NodeCheck(ByVal Node As MSComctlLib.Node)
Call CheckChild(TreeView1, Node) 'perform check on child nodes
'CheckChildren Node 'Call subroutine
End Sub
Private Sub CheckChild(Tree As TreeView, CurrentNode As Node)
Dim ParentIndex 'used to find out the index of the parent node from the child node that was clicked
Dim CheckChecked As Integer 'Used to decide whether or not parent is to be checked
Dim j As Integer 'Counter
On Error Resume Next
If CurrentNode.Checked = True Then 'If node is checked then check parent node ONLY if ALL child nodes are checked
If Tree.Nodes.item(CurrentNode.Index).Checked = True Then 'If "My Node"(My Node's Index) is checked then
ParentIndex = Tree.Nodes.item(CurrentNode.Index).Parent.Index 'locate index of parent node
For j = 1 To Tree.Nodes.item(ParentIndex).Children 'run loop to find out which child nodes
If Tree.Nodes.item(ParentIndex + j).Checked = False Then 'are checked and which are not...
CheckChecked = CheckChecked + 0 'unchecked and 1 for checked, add to
ElseIf Tree.Nodes.item(ParentIndex + j).Checked = True Then 'previous value
CheckChecked = CheckChecked + 1
End If
Next j
If CheckChecked = Tree.Nodes.item(ParentIndex).Children Then 'if the number of checked nodes is equal
Tree.Nodes.item(ParentIndex).Checked = True 'to number of child nodes then all child
Else 'nodes are checked so check parent node
Tree.Nodes.item(ParentIndex).Checked = False
End If
End If
ElseIf CurrentNode.Checked = False Then 'if the current node is unchecked then
ParentIndex = Tree.Nodes.item(CurrentNode.Index).Parent.Index 'uncheck the parent node as ALL child nodes
Tree.Nodes.item(ParentIndex).Checked = False 'must be checked to before the parent node is checked
End If
'To enable and disable checkboxes based on Parent Node CheckBox
Dim i As Integer, nodX As Node
If CurrentNode.Children <> 0 Then 'If node has children
Set nodX = CurrentNode.Child 'Catch first child
For i = 1 To CurrentNode.Children 'Loop through each child
nodX.Checked = CurrentNode.Checked 'Set as checked
'CheckChildren nodX 'Check to see if this node has children
Set nodX = nodX.Next 'Catch next child
Next 'Loop
End If
End Sub
Я ожидаю минимального кода.