Excel VBA: Why does combo box shows only one item in the list?

柔情痞子 提交于 2019-12-24 18:47:38

问题


I tried to make a combo box via VBA which will show in its drop down list a number of values in certain cells from worksheet. This is the relevant code:

Set header = ActiveWorkbook.Worksheets(source_sheet_1_name).Range(Cells(4, 4), Cells(4, 9))
ActiveWorkbook.Names.Add Name:="header", RefersTo:=header
UserForm2.ComboBox1.RowSource = "header"

However, combo box shows only the first item in the list. I looked into it for a day and still could not figure out what I did wrong.


回答1:


RowSource won't work with a horizontal list, but you can simply assign the range to the Column property of the combobox like this:

UserForm2.ComboBox1.Column = Header.Value



回答2:


Little workaround:

Set header = ActiveWorkbook.Worksheets(source_sheet_1_name).Range(Cells(4, 4), Cells(4, 9))
For Each cell In header
     UserForm2.ComboBox1.AddItem (cell.Value)
Next cell



回答3:


I created a vertical list and slightly tweaked the code. The form I created has a commandbutton and a combobox. clicking on the button sets the rowsource for the combobox (cbo1).

Option Explicit
Dim mylist As Range

Private Sub CommandButton1_Click()
Set mylist = ActiveWorkbook.Worksheets("lists").Range(Cells(4, 4), Cells(9, 4))
ActiveWorkbook.Names.Add Name:="header", RefersTo:=mylist
Me.cbo1.RowSource = "header"
End Sub

Hope this helps

Sybolt



来源:https://stackoverflow.com/questions/45161753/excel-vba-why-does-combo-box-shows-only-one-item-in-the-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!