Assuming your checkbox objects named A_Checkbox
, B_Checkbox
, etc., correspond to worksheets named exactly like "A"
, "B"
, etc., then something like:
Private Sub Add_Button_Click()
Dim ctrl As Control
For Each ctrl In UserForm1.Controls
If TypeName(ctrl) = "CheckBox" Then
'Pass this CheckBox to the subroutine below:
TransferValues ctrl
End If
Next
End Sub
REVISED
It looks like you are dumping the same data from the user form to each sheet, based on the check box selection(s). You won't need a case select statement for this, just define a worksheet
variable based on the CheckBox.Name
. Note that I changed this from a Function
to a Sub
although that shouldn't matter really. I also change this so the value of emptyRow
is calculated each time, since that will change depending on what worksheet you are acting on.
Sub TransferValues(cb As MSForms.CheckBox)
Dim ws As Worksheet
Dim emptyRow as Long
If cb Then
'Define the worksheet based on the CheckBox.Name property:
Set ws = Sheets(Left(cb.Name, 1))
emptyRow = WorksheetFunction.CountA(ws.Range("A:A")) + 1
With ws
.Cells(emptyRow, 1).Value = NOD_Text.Value
.Cells(emptyRow, 2).Value = TOD_Text.Value
.Cells(emptyRow, 3).Value = Program_Text.Value
.Cells(emptyRow, 4).Value = email_Text.Value
.Cells(emptyRow, 5).Value = OPN_Text.Value
.Cells(emptyRow, 6).Value = CPN_Text.Value
End With
End If
End Sub
Edit to clarify based on comments from OP
TypeName
is a built-in method that returns a string that identifies the type of object. In this case, we iterate over all controls on the user form, so you need some logic to make sure the function only operates on the CheckBox
controls.
cb
is a variable local to the TransferValues
subroutine. In the calling subroutine (CommandButton1_Click
in my example), we send the object ctrl
(a CheckBox control) to this subroutine.
The boolean statement If cb
simply evaluates whether the checkbox has been checked. You could do If cb.Value = True
but my personal preference is to simplify it.
UPDATED & TESTED
Here is a Before picture with an example userform containing three checkboxes and a few dummy textboxes:
Now here is the worksheet "C" after I have pressed the "Add" button:
And finally, I can continue to change the textbox values and press the add button over and over again, like so: