我有一个国家/地区列表和excel模型的方案列表。每个列表都有一个带有"所有国家/地区的复选框。和#34;所有场景"选项将选中与每个相关的所有复选框。当我点击"所有国家"复选框,正确选中每个国家/地区复选框。对于"所有场景"复选框。但是,如果我取消选择单个国家/方案,则仍会选中“所有国家/方案”框。
如何获得"所有国家"和#34;所有场景"取消选中子复选框时取消选中的复选框?
以下是我到目前为止的代码。
Sub SelectAll_Read()
Dim CB As CheckBox
For Each CB In ActiveSheet.CheckBoxes
If CB.Name <> ActiveSheet.CheckBoxes("MCB.1").Name And CB.Name <> ActiveSheet.CheckBoxes("MCB.2").Name Then
If Mid(CB.Name, 5, 1) = "1" Then
CB.Value = ActiveSheet.CheckBoxes("MCB.1").Value
ElseIf Mid(CB.Name, 5, 1) = "2" Then
CB.Value = ActiveSheet.CheckBoxes("MCB.2").Value
End If
End If
Next CB
End Sub
Sub Mixed_ReadState()
Dim CB As CheckBox
Dim i As String
For Each CB In ActiveSheet.CheckBoxes
i = Mid(CB.Name, 5, 1)
If CB.Name <> ActiveSheet.CheckBoxes("MCB" & i).Name And CB.Value <> ActiveSheet.CheckBoxes("MCB" & i).Value And ActiveSheet.CheckBoxes("MCB" & i).Value <> 2 Then
ActiveSheet.CheckBoxes("MCB" & i).Value = 2
Exit For
Else
ActiveSheet.CheckBoxes("MCB" & i).Value = CB.Value
End If
Next CB
End Sub
答案 0 :(得分:0)
如果您将此分配给工作表上的所有复选框,则它应处理同步主&lt;&gt;子状态。
Sub HandleClick()
Dim sht As Worksheet, nm As String
Dim arrA, arrB, masterClicked As Boolean
Dim c As CheckBox, cb As CheckBox
Dim mixedChildValues As Boolean
Set sht = ActiveSheet
nm = Application.Caller
Set cb = sht.CheckBoxes(nm) 'the clicked checkbox
arrA = Split(nm, ".") 'split the cb name on "." to give an array
masterClicked = (UBound(arrA) = 1) '"master" cb clicked?
mixedChildValues = False
'loop over all checkboxes on the sheet
For Each c In sht.CheckBoxes
'ignore the clicked checkbox
If c.Name <> nm Then
arrB = Split(c.Name, ".") 'split the name...
If arrA(1) = arrB(1) Then 'only consider same "family" of checkboxes
If masterClicked Then
'set all childern to "master" value if master was clicked
c.Value = cb.Value
Else
If (UBound(arrB) = 2) Then 'only look at children...
If c.Value <> cb.Value Then
mixedChildValues = True
Exit For 'no need to check further...
End If
End If 'child checkbox
End If
End If 'same family
End If 'not the clicked checkbox
Next c
'child checkbox was clicked - see if the master needs adjusting...
If Not masterClicked Then
sht.CheckBoxes(arrA(0) & "." & arrA(1)).Value = IIf(mixedChildValues, -4146, cb.Value)
End If
End Sub