在运行时添加事件以获取excel中userform中的复选框

时间:2016-07-25 13:00:03

标签: excel vba excel-vba checkbox

我试过@DaveShaw code,对于复选框的运行时事件,点击不是复选框的有效方法吗?它永远不会进入方法checkBoxEvent_click

Dim CheckBoxArray() As New ClassEvents          
for i=0 to 10  
          Set cTemp = MOM.Frame_MOM_MOM.Controls.Add("Forms.CheckBox.1")

            With cTemp
                .Top = HeaderOffset + RowOffset + i * 25 'your top pos
                .Visible = True
                .Left = 30  'your left pos
                .Width = widthOfLabel 'your width
                .Name = Replace(keyArrays(i, 1), " ", "_")
                .Caption = keyArrays(i, 1) 'your caption ,


            End With

            ReDim Preserve CheckBoxArray(0 To i)
            Set CheckBoxArray(i).checkBoxEvent = cTemp
            next i

我的ClassEvents类看起来像这样:

Public WithEvents checkBoxEvent As MSForms.checkBox

Private Sub checkBoxEvent_click()
    MsgBox "halla" 'checkBox.Caption
End Sub

1 个答案:

答案 0 :(得分:1)

您必须将Dim CheckBoxArray() As New ClassEvents放在userfom代码窗格的最顶层,因此不在其任何子/函数之外

此外也使用Option Explicit语句

它变成了

Option Explicit

Dim CheckBoxArray() As New ClassEvents '<--| keep this line at the very top of your userform code pane

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim cTemp As MSForms.CheckBox '<-- with "Option Explicit" you have to declare all your variables

    For i = 0 To 10
        Set cTemp = MOM.Frame_MOM_MOM.Controls.Add("Forms.CheckBox.1")
          With cTemp
             .Top = HeaderOffset + RowOffset + i * 25 'your top pos
              .Visible = True
              .Left = 30  'your left pos
              .Width = widthOfLabel 'your width
              .Name = Replace(keyArrays(i, 1), " ", "_")
              .Caption = keyArrays(i, 1) 'your caption ,
          End With
          ReDim Preserve CheckBoxArray(0 To i)
          Set CheckBoxArray(i).checkBoxEvent = cTemp
    Next i
End Sub

此外,由于您已经知道数组的维度,因此Dim在开头就知道它,并且在每次迭代时都不ReDim

Option Explicit

Dim CheckBoxArray(0 To 10) As New ClassEvents '<--| keep this line at the very top of your userform code pane

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim cTemp As MSForms.CheckBox '<-- with "Option Explicit" you have to declare all your variables

    For i = 0 To 10
        Set cTemp = MOM.Frame_MOM_MOM.Controls.Add("Forms.CheckBox.1")
          With cTemp
             .Top = HeaderOffset + RowOffset + i * 25 'your top pos
              .Visible = True
              .Left = 30  'your left pos
              .Width = widthOfLabel 'your width
              .Name = Replace(keyArrays(i, 1), " ", "_")
              .Caption = keyArrays(i, 1) 'your caption ,
          End With
          Set CheckBoxArray(i).checkBoxEvent = cTemp
    Next i
End Sub