Pherdindy
Pherdindy

Reputation: 1178

How to populate a combo box in the userforms with names from a column in my worksheet?

Below is the code I created:

Private Sub UserForm_Activate()

Dim Total_rows_PU As Long
Total_rows_PU = Workbooks("Revised-Payroll (VBA Copy).xlsm").Worksheets("Payroll Update").Range("A" & Rows.Count).End(xlUp).Row

Me.cbxName.List = Worksheets("Payroll Update").Range("A2:A" & Total_rows_PU)

End Sub

This is the error I receive:

Error Dialogue Box

This is where the error occurs: Line of Error

Working solution after considering the answer below:

Private Sub UserForm_Initialize()

Total_rows_PU = Workbooks("Revised-Payroll (VBA Copy).xlsm").Worksheets("Payroll Update").Range("A" & Rows.Count).End(xlUp).Row

Dim cell As Range

For Each cell In Range("A2:A" & Total_rows_PU)
    Me.cbxName.AddItem cell.Value
Next
End Sub

Upvotes: 0

Views: 88

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37377

Here's the right way of populating combobox:

Private Sub UserForm_Initialize()
Dim cell As Range

For Each cell In Range("A1:A9")
    Me.ComboBox1.AddItem cell.Value
Next

End Sub

It populates combobox with values from cells in range A1:A9 (you have to specifiy your own). Here's how it works:

enter image description here

Values indicate cell address :)

Of course, @TotsieMae pointed lot's of good resources - I recommend them :)

Upvotes: 1

Related Questions