How to create a generic combobox fill routine in Excel VBA?

Viewed 419

I would like to have a generic method for filling combo boxes in Microsoft Visual Basic for Application 7.1.

I tried to cast a control parameter to comboBox with CType but Excel doesn't recognize this function.

How can I fill a comboBox in a generic way?

1 Answers

The easiest way is through the name of the ComboBox. You do not have to cast a control to comboBox.

Public Sub FillComboBox(UserForm As UserForm, cbName As String, column As String, startRow As Integer)
    Dim dataSheet As Worksheet
    Dim Count As Integer
    Set dataSheet = Worksheets("yourWorksheetName")

    Count = WorksheetFunction.CountA(dataSheet.Range(column & startRow & ":" & column & "10000")) - 1
    UserForm.Controls(cbName).List = dataSheet.Range(column & startRow & ":" & column & startRow + Count).value
End Sub

The call in your UserForm or wherever looks like this:

FillComboBox Me, Me.cbMyComboBox.name, "A", 1
Related