Search code examples
vbacheckboxuserform

Is there a way to select a TextBox input if a checkbox is ticked? VBA Excel


As you can see in the below image, I have several checkboxes representing measures and the last two are supposed allow for additional measures. The textboxes on the front allow the user to specify the name of their measure.

enter image description here

I was able to successfully send the name (caption) of the ticked checkboxes to a Listbox using the following code:

Dim ctrl As Control

For Each ctrl In Me.Controls
    If TypeName(ctrl) = "CheckBox" Then
        If ctrl.Value = True Then
            ListBox1.AddItem ctrl.Caption
        End If
    End If
Next ctrl

However, if the user selects the "Additional measures" checkbox I want what they inputted in the textboxes to be added to the list box, instead of the checkbox caption.

Is there any way I can do that?


Solution

  • To keep the code simple, you may want work with Tags instead of Captions

    Private Sub CommandButton1_Click()
        Dim ctl As Control
        For Each ctl In Me.Controls
            If TypeName(ctl) = "CheckBox" Then
                If ctl.Value And ctl.Tag <> "" Then
                    ListBox1.AddItem ctl.Tag
                End If
            End If
        Next ctl
    End Sub
    
    Private Sub TextBox1_Change()
        Me.CheckBox4.Tag = Me.TextBox1.Text
    End Sub
    
    Private Sub TextBox2_Change()
        Me.CheckBox5.Tag = Me.TextBox2.Text
    End Sub
    

    Edit: Added the condition And ctl.Tag <> ""