I think this is less complicated than I am making it but being a novice with VBA I haven't been able to find the answer after a couple days of googling and playing with different code.
I have a macro that:
I now need the user to click which checkboxes they want and then the captions for these checkboxes to be saved as an array that I can then call on later in the macro.
ie if they clicked dog, cat, and bird from the checkboxes, the output would be dog,cat,bird
Because of the variable length of the range and number of checkboxes, I can't figure out how to have it loop through each one and concatenate the correct values.
I think there is probably a way to cut out the copy pasting of the values to populate the userform with also, but this was the only way I could figure out that part given the variable length of the range.
Below is the code that generates the userform after the range has been copy pasted.
Private Sub UserForm_Initialize()
Dim curColumn As Long
Dim i As Long
Dim codeRow As Long
Dim chkBox As msforms.CheckBox
curColumn = 15
codeRow = Range("O20").End(xlUp).Row
For i = 1 To codeRow
Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
chkBox.Caption = Worksheets(1).Cells(i, curColumn).Value
chkBox.Left = 5
chkBox.Top = 5 + ((i - 1) * 20)
Next i
End Sub
Insert moduel code.
Public vCheck()
Bellows in form code.
Private Sub UserForm_Initialize()
Dim curColumn As Long
Dim i As Long
Dim codeRow As Long
Dim chkBox As msforms.CheckBox
curColumn = 15
codeRow = Range("O20").End(xlUp).Row
ReDim vCheck(0)
For i = 1 To codeRow
Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
ReDim Preserve vCheck(1 to i)
vCheck(i) = Worksheets(1).Cells(i, curColumn).Value
chkBox.Caption = vCheck(i)
chkBox.Left = 5
chkBox.Top = 5 + ((i - 1) * 20)
Next i
End Sub
Listbox was the way to go. Here is the updated code for others looking for help with the same issue:
Private Sub UserForm_Initialize()
Dim myLBox As msforms.ListBox
Dim codeRow As Long
codeRow = Range("O20").End(xlUp).Row
ListBox1.RowSource = "O1:O" & codeRow
End Sub
Private Sub CommandButton1_Click()
Dim rRange As Range
Dim lCount As Long 'Counter
On Error GoTo ErrorHandle
Set rRange = Range("P1")
With ListBox1
For lCount = 0 To .ListCount - 1
If .Selected(lCount) = True Then
rRange.Offset(lCount, 0).Value = .List(lCount)
End If
Next
End With
BeforeExit:
Set rRange = Nothing
Unload Me
Exit Sub
ErrorHandle:
MsgBox Err.Description
Resume BeforeExit
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.