I have a user in which I am creating 7 checkboxes programmatically, and removing the same using 2 command buttons. Now, I am facing issues when I am trying to read/ store the value of a checkbox when clicked.
I have used the Class Module -
Public WithEvents cBox As MSForms.CheckBox
Private Sub cbox_click()
msgbox cBox.Name & " clicked. Value is now " & IIf(cBox.Value, "Checked", "Unchecked")
End Sub
And in UserForm -
Dim chkBoxEvent As clsBoxEvent
Dim chkBoxColl As Collection
Private Sub btnAddClass_Click()
Dim ctrl As Control, newCtrl As Control, offsetTop As Integer
Set chkBoxColl = New Collection
offsetTop = 36
For Each ctrl In Me.Controls
If TypeName(ctrl) <> "CommandButton" Then
If ctrl.Top = btnAddClass.Top - offsetTop Then
If TypeName(ctrl) = "ComboBox" Then
Set newCtrl = Me.Controls.Add("Forms.ComboBox.1")
ElseIf TypeName(ctrl) = "TextBox" Then
Set newCtrl = Me.Controls.Add("Forms.TextBox.1")
End If
nchk = 7
If TypeName(ctrl) = "CheckBox" Then
For i = 1 To nchk
Set newCtrl = Me.Controls.Add("Forms.Checkbox.1")
With newCtrl
.Height = ctrl.Height
.Width = ctrl.Width
.Top = ctrl.Top + offsetTop
.Left = ctrl.Left
.Tag = nchk * 10
End With
Set chkBoxEvent = New clsBoxEvent
Set chkBoxEvent.cBox = Me.Controls(newCtrl.Name)
chkBoxColl.Add chkBoxEvent
Next
End If
If TypeName(newCtrl) <> "CheckBox" Then
With newCtrl
.Height = ctrl.Height
.Width = ctrl.Width
.Top = ctrl.Top + offsetTop
.Left = ctrl.Left
End With
End If
End If
End If
Next ctrl
btnAddClass.Top = btnAddClass.Top + offsetTop
btnRemoveClass.Top = btnRemoveClass.Top + offsetTop
Me.Height = Me.Height + offsetTop
End Sub
Private Sub btnRemoveClass_Click()
Dim ctrl As Control, offsetTop As Integer
offsetTop = 36
For Each ctrl In Me.Controls
If TypeName(ctrl) <> "CommandButton" Then
If ctrl.Top = btnAddClass.Top - offsetTop Then
Me.Controls.Remove (ctrl.Name)
End If
End If
Next ctrl
btnAddClass.Top = btnAddClass.Top - offsetTop
btnRemoveClass.Top = btnRemoveClass.Top - offsetTop
Me.Height = Me.Height - offsetTop
End Sub
Each time new set of checkboxes are added, the msgbox
displays as "CheckBox22, 99, 110, 789" etc random numbers.
Aucun commentaire:
Enregistrer un commentaire