简体   繁体   中英

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

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?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM