Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add checkboxes to UserForm based on cell value

I'm very new to VBA, just 3 days... but i found it very useful and easy to use, but now i'm facing a problem. I need to make a UserForm with different Checkboxes, but i need them to be added automatically based on the information used in one of the columns of a Sheet. I believe i can use the For .. Each .. Next but i really don't know how to fill the Checkboxes. This is the only solution that i have right now, but i can't make differents Checkboxes, only one.

For Each rCell In Range("B1:B" & LastRow)
    If rCell.Value <> "" Then
        UserForm1.Controls.Add ("Forms.CheckBox.1")
    End If
Next

One more thing that i need to do is fill the properties of the Checkbox once it is added, so i can work with the values after that.

Any help would be appreciated, Thanks!

like image 824
hcsnemrebured Avatar asked Mar 20 '13 17:03

hcsnemrebured


1 Answers

I'm sure you've gotten your answer before now, but since this came up in a Google search of mine, I thought I'd post another answer. Place the following code in your UserForm:

Option Explicit

Private Sub UserForm_Initialize()

Dim curColumn   As Long
Dim LastRow     As Long
Dim i           As Long
Dim chkBox      As MSForms.CheckBox

curColumn = 1 'Set your column index here
LastRow = Worksheets("Sheet1").Cells(Rows.Count, curColumn).End(xlUp).Row

For i = 1 To LastRow
    Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
    chkBox.Caption = Worksheets("Sheet1").Cells(i, curColumn).Value
    chkBox.Left = 5
    chkBox.Top = 5 + ((i - 1) * 20)
Next i

End Sub

You will need to modify the code to suit your specific needs, but that will get you started.

like image 134
TheEngineer Avatar answered Dec 29 '22 01:12

TheEngineer