限制树视图选择 VBA

Limit Treeview selection VBA

我想将我的 Treeview 选择限制为最多 8 个子节点。我有以下代码,它确实取消选中该框,但在再次选择该框后立即。有什么想法吗?

谢谢。

Private Sub TreeView1_NodeCheck(ByVal node As MSComctlLib.node)

If Not node.Parent Is Nothing Then
    If node.Checked = True Then
      couT = couT + 1
      If couT <= 8 Then
          'MsgBox node.Text & "_Checked !"
      Else
          node.Checked = False
      End If
    Else
      couT = couT - 1
    End If
End If

结束子

这个 TreeView NodeCheck 对象不像其他对象那样处理事件,在 Sub 完成后设置 .Checked = False 没有任何意义。但是,有一种解决方法是在普通模块中使用 Public 变量和 Sub,最重要的是 Application.OnTime 来取消检查(在宏中完成时不会触发 _NodeCheck) .

因此,在带有 TreeView 对象的用户窗体模块中:

Private couT As Integer
Private Const MAX_NODES As Integer = 8

Private Sub TreeView1_NodeCheck(ByVal Node As MSComctlLib.Node)
    Dim bSchUncheckNode As Boolean
    bSchUncheckNode = False
    If Not Node.Parent Is Nothing Then
        If Node.Checked = True Then
            couT = couT + 1
            If couT <= MAX_NODES Then
                'Debug.Print Node.Text & "_Checked !"
            Else
                couT = couT - 1 ' Assuming the scheduled task completes successfully (or move the variable to standard module).
                bSchUncheckNode = True
                iNodeToUncheck = Node.Index
            End If
        Else
            couT = couT - 1
        End If
    End If
    ' Schedule Sub call only if it should uncheck a node
    If bSchUncheckNode Then Application.OnTime Now, "UncheckNode"
End Sub

Sub UserForm_Initialize()
    couT = 0 ' Resets the counter to zero
    '... Other things you have had
End Sub

在普通的 vba 模块中(相应地更改 UserForm 和 TreeView 对象的名称):

Public iNodeToUncheck As Integer

Sub UncheckNode()
    ' Assuming this is only be called by the UserForm scheduling
    UserForm1.TreeView1.Nodes(iNodeToUncheck).Checked = False
End Sub