I created a CheckBox list as each category is inserted into the database. However, I'm not able to capture the click event of these dynamically created CheckBoxes. Does anyone know where the error is?
Public Sub CarregarCheckBoxCategoria(Categoria As String)
Dim Cont As Integer
Set chkCheckBox = frmProdutos.Frame3.Controls.Add("Forms.CheckBox.1", "NovoCheckBox", True)
PositionTop = PositionTop + 12
With chkCheckBox
.Name = RemoverCaracter(Categoria)
.Caption = Categoria
.Width = 72
.Height = 18
.Top = .Top + PositionTop
.Left = 186
End With
End Sub
Private Sub NovoCheckBox_Click()
If CheckBox1.Value = True Then
MsgBox "CheckBox has selected"
Else
MsgBox "CheckBox has not selected"
End If
End Sub
I changed the above code, however, only the last checkbox executes the Click event. Here is my code:
UserForm
Public Sub CarregarCheckBoxCategoria(Categoria As String)
Dim CheckBox As Control
ReDim CheckBoxs(iChk)
Set CheckBox = frmProdutos.Frame3.Controls.Add("Forms.CheckBox.1", "NovoCheckBox", True)
PositionTop = PositionTop + 12
With CheckBox
.Name = RemoverCaracter(Categoria)
.Caption = Categoria
.Width = 72
.Height = 18
.Top = .Top + PositionTop
.Left = 186
End With
Set CheckBoxs(iChk).Ctrl = CheckBox
iChk = iChk + 1
End Sub
Module
Option Explicit
Public CheckBoxs() As New CheckBoxHandler
Public iChk As Integer
Public PositionTop As Integer
Private Conn As ADODB.Connection
Private rst As ADODB.Recordset
Public Sub ExtrairCategoria()
iChk = 0
Dim strQuery As String
strQuery = "SELECT CategoryName FROM dbo.Categories ORDER BY CategoryName"
Set rst = New ADODB.Recordset
rst.Open strQuery, Conn, adOpenForwardOnly, adLockOptimistic
frmProdutos.cmbCategoria.Clear
Do While Not rst.EOF()
frmProdutos.cmbCategoria.AddItem rst!CategoryName
Call frmProdutos.CarregarCheckBoxCategoria(rst!CategoryName)
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
End Sub
In the CheckBoxHandler class
Option Explicit
Public WithEvents Ctrl As MSForms.CheckBox
Private Sub Ctrl_Click()
MsgBox "Você clicou no CheckBox de nome " & Ctrl.Name
End Sub