简体   繁体   English

用VBA中的值填充组合框

[英]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. 用户通过引用选择范围,然后必须使用所选单元格的值填充ComboBox 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. 我本身并没有附加到ComboBox ,但是我需要使用列中的值填充列表,以便用户可以选择要用作“键”的列表。第一组是示例中的内容。行。 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 您可以在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. 这将添加指定范围内的所有项目,而不是通过1对其进行遍历。

Edit 1: 编辑1:

Dim list as variant

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

cmbkeyCol.List = list

Hope this works. 希望这行得通。

Edit 2: 编辑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. 我假设selRng是Edit 1中的源范围,实际上它是rngHeader。 Hopefully this works now. 希望这现在可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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