检查checkbox的值,并相应地设置所有其他checkbox的值

我想创build一个像“Mastercheckbox”的东西,它会自动检查我的工作表上的所有其他checkbox。 所以我试图启动下面的VBA代码,只要我点击“Mastercheckbox”我使用表单工具而不是活动X创build我的checkbox,以确保我的VBA与任何机器兼容(我读Active X可能会导致一些问题),并得到了以下代码:

Sub Mastercheckbox() Dim Chk As CheckBox With ActiveSheet.Shapes("Mastercheckbox") If .ControlFormat.Value = False Or .ControlFormat.Value = True Then If .ControlFormat.Value = False Then For Each chk In ActiveSheet.CheckBoxes If Not chk.Name = "Mastercheckbox" Then chk.Value = False End If Next chk End If If Not .ControlFormat.Value = True Then For Each chk In ActiveSheet.CheckBoxes If Not chk.Name = "Mastercheckbox" Then chk.Value = True End If Next chk End If Else: MsgBox ("couldn't check value of mastercheckbox") End If End With End Sub 

“For Loops”中的所有内容都可以正常工作,但是检查Mastercheckbox的值只是因为某种原因而不起作用,并且会直接跳转到其他情况。 谁能帮我吗?

不是一个ActiveX控件,你必须检查它的值对xlOn (对应于1)和xlOff (对应-4146)

你也可以重构一下你的代码,如下所示:

 Option Explicit Sub Mastercheckbox() With ActiveSheet.Shapes("Mastercheckbox") If .ControlFormat.Value = xlNone Then MsgBox ("couldn't check value of mastercheckbox") Else HandleCheckBoxes .ControlFormat.Value End If End With End Sub Sub HandleCheckBoxes(val As Long) Dim Chk As CheckBox For Each Chk In ActiveSheet.CheckBoxes If Not Chk.name = "Mastercheckbox" Then Chk.Value = val Next Chk End Sub 

由于您决定使用User_Formcheckbox,因此您需要将variables定义为Shape 。 而为了检查他们的价值,你需要检查他们是否是xlOnxlOff

为了看到你按下了“Mastercheckbox”的值,你可以使用下面的代码:

 Dim MasterCB As Shape Set MasterCB = ActiveSheet.Shapes("Mastercheckbox") '<-- set the MasterCB variable If MasterCB.ControlFormat.Value = xlOn Then MsgBox "Is checked" ElseIf MasterCB.ControlFormat.Value = xlOff Then MsgBox "Not checked" End If 

代码为您的文章

 Option Explicit Sub Mastercheckbox() Dim Chk As Shape Dim MasterCB As Shape ' set the MasterCB variable Set MasterCB = ActiveSheet.Shapes("Mastercheckbox") ' loop through all shapes in ActiveSheet For Each Chk In ActiveSheet.Shapes If Chk.Type = msoFormControl Then '<-- check your shape type is User_Form type If Chk.FormControlType = xlCheckBox Then '<-- check if the shape is a checkbox If Chk.Name <> "Mastercheckbox" Then Chk.ControlFormat.Value = MasterCB.ControlFormat.Value '<-- modify all checkboxes to the value of "Mastercheckbox" End If End If End If Next Chk End Sub