Excel命令按钮同时选中和取消选中某些Active-X复选框

时间:2017-03-07 16:44:39

标签: excel vba excel-vba

我正在尝试使用Excel中的Active-X Command按钮来选择某些复选框并同时取消选中其他复选框。现在,我希望取消选中所有以“Design”开头或包含名称“Design”的方框,同时检查所有以“Checkbox”开头或包含名称“Checkbox”的方框。

下面的代码用于取消选中名称中包含“Design”的框,但自从我添加了以“Checkbox”开头的框的检查后,我收到错误(对象的方法“名称”) _OLEOBJECT'失败)。

    Private Sub CommandButton1_Click()

    Dim o As Object
        For Each o In ActiveSheet.OLEObjects
            If InStr(1, o.Name, "Design") > 0 Then
                o.Object.Value = False
            ElseIf InStr(1, o.Name, "CheckBox") < 1 Then
                    o.Object.Value = True
            End If
        Next                      
    End Sub

我也尝试过这种变化,但仍会产生与上述相同的错误:

Private Sub CommandButton1_Click()

    Dim o As Object
        For Each o In ActiveSheet.OLEObjects
            If InStr(1, o.Name, "Design") > 0 Then
                o.Object.Value = False
            End If
        Next

    Dim j As Object
         For Each j In ActiveSheet.OLEObjects
             If InStr(1, j.Name, "CheckBox") < 1 Then
                j.Object.Value = True
            End If
        Next


    End Sub

1 个答案:

答案 0 :(得分:0)

试试这个,取消选中所有复选框。如果要检查所有复选框,只需将其设置为true。

Sub uncheck_all()
    Dim sh As Shape
    Application.ScreenUpdating = False
    For Each sh In ActiveSheet.Shapes
        If sh.Type = msoOLEControlObject Then
            If TypeName(sh.OLEFormat.Object.Object) = "CheckBox" Then sh.OLEFormat.Object.Object = True    'set to true if you want to check all checkboxes
        End If
        If sh.Type = msoFormControl Then
            If sh.FormControlType = xlCheckBox Then sh.OLEFormat.Object = True    'set to true if you want to check all checkboxes
        End If
    Next sh
    Dim o As Object
    For Each o In ActiveSheet.OLEObjects
        If o.Name Like "Design*" Then 'use  If o.Name Like "*Design*" Then if you want to be any name with "Design" in the name.
            o.Object.Value = False
        End If
    Next o
    Application.ScreenUpdating = True
End Sub