yuro
yuro

Reputation: 2209

Checkbox event doesn't work in VBA

I dynamically defined checkboxes, which are added to the userform on runtime.

Sub Userform_Initialize()
  For i = 1 To 4
    Set Chk = Frame4.Controls.Add("Forms.Checkbox.1", "Checkbox" & i)
    With Chk
       .top = 84 + k
       .left = 336
       .Width = 100
       .Height = 18
       .Caption = "Add item"
       .Visible = True
    End With
    k = k + 24
  Next i
End Sub

Public WithEvents Chk As MSForms.CheckBox
Private Sub Chk_Click()
    MsgBox Chk
End Sub

For some reason, the event doesn't respond. Does anyone have an idea as to why? I need the boolean of the checkbox. That means when the user clicked on a dynamic checkbox, then I see "True" returned in the msgbox.

Upvotes: 0

Views: 513

Answers (1)

user3598756
user3598756

Reputation: 29421

Add a class module to your project, name it as you want (say "ChkBox"), and put this code in it:

Public WithEvents Chk As MSForms.CheckBox

Private Sub Chk_Click()
    MsgBox Chk.Value
End Sub

In your userform code, add this

Dim myChks(1 To 4) As New ChkBox '<--| this must be at the very top of your userform code pane

Sub Userform_Initialize()
    Dim i As Long, k As Long

    With Me.Frame4.Controls
        For i = 1 To 4
            With .Add("Forms.Checkbox.1", "Checkbox" & i)
                .Top = 84 + k
                .Left = 336
                .Width = 100
                .Height = 18
                .Caption = "Add item"
                .Visible = True
                Set myChks(i).Chk = .Parent.Item(.Name)
            End With
            k = k + 24
        Next i
    End With
End Sub

Upvotes: 1

Related Questions