简体   繁体   中英

Filling a combobox with values in VBA

I am having trouble filling a combobox with options from a range.

The user selects the range with a refedit, the ComboBox must then be populated with the values of the selected cells. If the user changes the ref the old data must be removed and repopulated with the new data.

Below is my current code. Compiles right, but doesn't work.

I'm not attached to a ComboBox per se, but I need to populate a list with the values from a column so the user can select the one they want to use as "key" The first set is a sample of what is in a row. I would want these options offered as the choices for the dropdown.

You can download a copy of what I'm working on at http://ge.tt/2dbV5Yt/v/0?c

Store #    Address City    ST  Zip Market  Radius
Private Sub rngHeader_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Dim selRng As Range
    Set selRng = Range(rngHeader.Value)

    '//Erase any items that are in there
    For I = 1 To cmbKeyCol.ListCount
        cmbKeyCol.RemoveItem 0 'Remove the top item each time
    Next I


    'Below here is the part that I'm having trouble with. This is one of my attempts, but
       'I've changed this thing probably 20 times since asking the question
    '//Build  new list of items from the header row.
    For Each cell In selRng.Cells
        cmbKeyCol.AddItem cell.Value
    Next
End Sub

why don't you use this instead:

cmbkeyCol.RowSource = selRng.Address 'Assuming you already got your range right.

This adds all the items in the range specified instead of iterating through them 1 by 1.

Edit 1:

Dim list as variant

list = selRng.Value
list = Application.Transpose(list)

cmbkeyCol.List = list

Hope this works.

Edit 2:

Dim list as variant

list = rngHeader.value
list = Application.Transpose(list)

cmbkeyCol.List = list

I assumed that selRng is the source range in Edit 1 well in fact it is rngHeader. Hopefully this works now.

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