对于Array中的每个Checkbox

时间:2017-02-22 01:54:16

标签: excel-vba vba excel

我试图根据选项按钮隐藏一堆复选框,但我一直得到"错误1004:应用程序定义或对象定义错误":

Sub FU_EAL_PA_Toggle()
Dim cb As CheckBox
Dim MyCheckboxes As Variant
MyCheckboxes = Array( _
    "FU_EAL_PA1", _
    "FU_EAL_PA2", _
    "FU_EAL_PA3", _
    "FU_EAL_PA4", _
    "FU_EAL_PA5", _
    "FU_EAL_PA6", _
    "FU_EAL_PA7", _
    "FU_EAL_PA8", _
    "FU_EAL_PA8", _
    "FU_EAL_PA9", _
    "FU_EAL_PA10")

If ActiveSheet.OptionButtons("FU_PA_NotAttendingEAL").Value = 1 Then
    For Each cb In ActiveSheet.CheckBoxes(MyCheckboxes)
        With ActiveSheet.CheckBoxes(MyCheckboxes)
            .Enabled = True
            .Visible = True
        End With
    Next cb
Else
    For Each cb In ActiveSheet.CheckBoxes(MyCheckboxes)
        With ActiveSheet.CheckBoxes(MyCheckboxes)
            .Enabled = False
            .Visible = False
        End With
    Next cb
End If

End Sub
  1. 有更好的方法吗? (请注意,我将为另一个按钮子集重复此代码,因此我无法循环浏览工作表上的所有控件。)
  2. 我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

编辑:已更新以反映您的更改

Sub FU_EAL_PA_Toggle()

    Dim cb As CheckBox
    Dim bOK as Boolean
    Dim MyCheckboxes As Variant
    MyCheckboxes = Array( _
        "FU_EAL_PA1", _
        "FU_EAL_PA2", _
        "FU_EAL_PA3", _
        "FU_EAL_PA4", _
        "FU_EAL_PA5", _
        "FU_EAL_PA6", _
        "FU_EAL_PA7", _
        "FU_EAL_PA8", _
        "FU_EAL_PA8", _
        "FU_EAL_PA9", _
        "FU_EAL_PA10")

    bOK = (ActiveSheet.OptionButtons("FU_PA_NotAttendingEAL").Value = 1)

    For Each cb In MyCheckboxes
        With ActiveSheet.CheckBoxes(cb)
                .Enabled = bOK
                .Visible = bOK
        End With
    Next cb

    'or without the array...
    For x = 1 To 10
        With ActiveSheet.CheckBoxes("FU_EAL_PA" & x)
                .Enabled = bOK
                .Visible = bOK
        End With
    Next x

End Sub

答案 1 :(得分:0)

我能够找到一种解决方法(但是:阅读到底部,因为这是一种更简单的方法):

我没有构建一个数组来管理我的分组,而是意识到我的命名约定足以允许分组:

Public Sub FU_EAL_PA_ToggleNew()

Dim cb As CheckBox

If ActiveSheet.OptionButtons("FU_PA_NotAttendingEAL").Value = 1 Then
    For Each cb In ActiveSheet.CheckBoxes
        If Left(cb.Name, 9) = "FU_EAL_PA" Then
            cb.Visible = True
            cb.Enabled = True
        End If
    Next cb
Else
    For Each cb In ActiveSheet.CheckBoxes
        If Left(cb.Name, 9) = "FU_EAL_PA" Then
            cb.Visible = False
            cb.Enabled = False
        End If
    Next cb
End If

End Sub

但是,Slai上面的回答更简单:

  

您可以将控件[excelforcommerce.com/grouping-checkboxes-in-excel] [1]分组(或将它们放入Group Box控件中),然后执行以下操作:

ActiveSheet.Shapes("FU_EAL_PA").Visible = _
(ActiveSheet.OptionButtons("FU_PA_NotAttendingEAL").Value = 1)

我做了什么,它完全符合预期。

谢谢!