我有一个userform,它由复选框动态填充。为了提高可用性,我添加了一个复选框"全选"选择或取消选中所有复选框。这非常有效。现在我想要"选择全部"复选框一旦取消选中其他复选框,就会自动取消选中(值= False)。
为了实现这一目标,我创建了一个类模块。这个类模块也做了它应该做的事情。但是,这就是我的问题,一旦" Select all"改变了,"全选" checkbox_click事件被触发,这意味着所有其他复选框也被取消选中,这显然不是我想要的!我已经尝试过使用MouseDown和MouseUp事件,但这些事件表现不规律,往往会导致错误的结果。
问题:每次更改此复选框的值时,如果未实际点击该复选框,如何停止Click事件的运行?
这是我的代码:
Private colTickBoxes As Collection
Private Sub UserForm_Initialize()
Dim ChkBoxes As cls_RIRI
Dim ctrl As Control
'Controls are created on run time here
'Some events to change the height of the userform and the top value of several buttons
'Make sure click events work
Set colTickBoxes = New Collection
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" And Left(ctrl.Name, 1) = "M" Then
Set ChkBoxes = New cls_RIRI
ChkBoxes.AssignClicks ctrl
colTickBoxes.Add ChkBoxes
End If
Next ctrl
Set ctrlCHK = Nothing
Set ChkBoxes = Nothing
Set ctrl = Nothing
End Sub
类模块:
Private WithEvents chkBox As MSForms.CheckBox
Public Sub AssignClicks(ctrl As Control)
Set chkBox = ctrl
End Sub
Private Sub chkBox_Click()
If chkBox.value = False Then UserForms(0).Controls("chkSelAll").value = False
End Sub
chkSelAll_Click子:
Private Sub chkSelAll_Click()
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" And Left(ctrl.Name, 1) = "M" Then
If chkSelAll.value = True Then
ctrl.value = True
Else
ctrl.value = False
End If
End If
Next
Set ctrl = Nothing
End Sub
答案 0 :(得分:2)
添加一个公共变量,比如blnBypassNonUIClick并设置它,然后当来自UI时,通过人工点击将其设置为false,并且当设置select时全部相同。如果您按代码设置.value,则选择全部,不应激活click。像这样......
Public blnNonUI As Boolean
Private Sub CheckBox1_Click()
If Not blnNonUI Then
MsgBox "hello"
End If
End Sub
Private Sub UserForm_Click()
blnNonUI = True
Me.CheckBox1.Value = 1
blnNonUI = False
End Sub
答案 1 :(得分:0)
Nathan_Sav给了我这个想法并且它有效:
Public blnHumanClick As Boolean
Private Sub chkSelAll_Click()
If blnHumanClick = True Then
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" And Left(ctrl.Name, 1) = "M" Then
If chkSelAll.value = True Then
ctrl.value = True
Else
ctrl.value = False
End If
End If
Next
Set ctrl = Nothing
blnHumanClick = False
End If
End Sub
Private Sub chkSelAll_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
blnHumanClick = True
End Sub