2
I created a checkbox list as each category is entered into the database. However, I am unable 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 runs the Click event. Follow 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
I have the impression that yours
ReDim
is wrong. Compare in my original code there in the other question. It uses Resize only to set the final size of the array. In your case, you’re trying to make it grow dynamically (with each call). In this case, the array loses all existing content. You should have usedPreserve
on the call ofReDim
(take a look in the documentation).– Luiz Vieira
Another thing that seems wrong is that the
ReDim
expects the indexes or the size of the array. As you use the size, I think it should beiChk+1
(otherwise he’ll always have one less than necessary).– Luiz Vieira
Luiz, I included the preserve and it worked perfectly. I will look at the other suggestion about size to see if this change will influence something. But the first suggestion already solved my problem. Thanks for your help!
– Kelly Soares