首页 > 解决方案 > 如果未选中多个其他 Chechbox 之一,则取消选中 CheckBox1

问题描述

UserForm1由四个组成Checkboxes

CheckBox1 --> 主复选框
CheckBox2 --> 子复选框
CheckBox3 --> 子复选框
CheckBox4 --> 子复选框

现在,如果用户使用此 VBA 选中/取消选中 get 自动选中/取消选中CheckBox1sub CheckBoxes 2-4

Private Sub CheckBox1_Change()
If CheckBox1.Value = True Then
    CheckBox2.Value = True
    CheckBox3.Value = True
    CheckBox4.Value = True
Else
    CheckBox2.Value = False
    CheckBox3.Value = False
    CheckBox4.Value = False
End If
End Sub

这一切都完美无缺。


但是,现在我想实现这一点,以防其中一个sub CheckBoxes 2-4被取消main checkbox选中,并且自动取消选中而不取消选中另一个sub CheckBoxes.

示例:
用户首先单击CheckBox1,然后Checkboxes 2-4自动选中。
然后用户取消选中Checkbox2CheckBox1自动取消选中,而Checkbox 3-4保持选中状态。

像这样的东西:

Sub Check_Uncheck()
If any of Checkbox 2-4 is unchecked then
only uncheck CheckBox1 but do not change any other sub CheckBox
End

标签: excelvba

解决方案


使用UserForm作用域变量让更改事件处理或不处理它们的代码:

Option Explicit

Dim blockChange As Boolean

Private Sub CheckBox1_Change()
    If Not blockChange Then
        blockChange = True
        If CheckBox1 Then
            CheckBox2.Value = True
            CheckBox3.Value = True
            CheckBox4.Value = True
        Else
            CheckBox2.Value = False
            CheckBox3.Value = False
            CheckBox4.Value = False
        End If
        blockChange = False
    End If
End Sub

Private Sub CheckBox2_Click()
    OnOff
End Sub

Private Sub CheckBox3_Click()
    OnOff
End Sub

Private Sub CheckBox4_Click()
    OnOff
End Sub


Private Sub OnOff()
    If Not blockChange Then
        blockChange = True
        CheckBox1.Value = CheckBox2 And CheckBox3 And CheckBox4
        blockChange = False
    End If
End Sub

推荐阅读