How to Populate a Combobox

前端 未结 3 525
忘掉有多难
忘掉有多难 2021-01-13 01:26

I\'m quite new to VBA and I\'ve been struggling with populating a combobox. I\'m trying to fill a combobox with the contents of the first column in a spreadsheet so I can de

3条回答
  •  暖寄归人
    2021-01-13 02:11

    Private Sub UserForm_Initialize()
    
        Dim CS As Integer
        Dim CR As Integer
        Dim RF As Integer
        Dim PW As Integer
        Dim CD As Integer
    
            CS = ActiveWorkbook.Sheets("LISTS").Columns(2).End(xlDown).Row      
            CR = ActiveWorkbook.Sheets("LISTS").Columns(3).End(xlDown).Row      
            RF = ActiveWorkbook.Sheets("LISTS").Columns(4).End(xlDown).Row      
            PW = ActiveWorkbook.Sheets("LISTS").Columns(5).End(xlDown).Row      
            CD = ActiveWorkbook.Sheets("LISTS").Columns(6).End(xlDown).Row      
    
        With CB_CS
            .Clear
            For i = 2 To CS + 1
                .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 2).Value
            Next i
        End With
    
        With CB_CR
            .Clear
            For i = 2 To CR + 1
                .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 3).Value
            Next i
        End With
    
        With CB_RF
            .Clear
            For i = 2 To RF + 1
                .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 4).Value
            Next i
        End With
    
        With CB_PW
            .Clear
            For i = 2 To PW + 1
                .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 5).Value
            Next i
        End With
    
        With CB_CD
            .Clear
            For i = 2 To CD + 1
                .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 6).Value
            Next i
        End With
    End Sub
    

    The code above is located in my UserForm Code (Right-Click on UserForm, then click 'view code')

    I created a Worksheet call LISTS. Each column on that sheet is for a different combo-box. Once I filled it out and got the code working I hid the LISTS worksheet.

    Each ComboBox I named CB_XX so note those names in the code

    I start the code by defining the length of the lists (note this fails if you only have one item in the list but if you only have one item don't use a combo box)

    Once I get the lengths I add the correct columns to the correct comboboxes. Note the +1 in each for/next loop. That is to add a blank at the end of each list to allow the user to empty the selection. Remove the +1 if you don't want that blank. I start at i = 2 to not show the header row on my LISTS sheet.

提交回复
热议问题