Using RowSource Property to Fill ComboBox in Excel VBA

China☆狼群 提交于 2020-01-16 09:11:29

问题


I am trying to fill a ComboBox with selections equal to the first column of a data table, and keep getting

Run-Time error 380

I suppose I could use a loop and AddItem statements, but since I expect this to get large (several hundred entries), would prefer to stay away from loops that might slow down the execution. Any thoughts on what I am doing wrong?

Private Sub ClientNameComboxAdd_Enter()
Dim sht As Worksheet
Dim LastRow As Long, UseRow As Long
Dim NameFind As Range
Set sht = ThisWorkbook.Worksheets("Client Info")
LastRow = sht.ListObjects("Clients").Range.Rows.Count
If LastRow = 2 And sht.ListObjects("Clients").DataBodyRange(1, 1) = "" Then
    MsgBox "Can't Add a New Plan With No Clients Entered"
    Exit Sub
End If
ClientNameComboxAdd.RowSource = sht.ListObjects("Clients").ListColumns(1).DataBodyRange
End Sub

The problem is in the next-to-last line - ClientNameComboxAdd.RowSource ... The first part, which comes into play before clients are added to the table, seems to work fine.

Any thoughts would be appreciated.


回答1:


I did it this way. No VBA code at all. Just Excel 100%.

First, I created a Table named "T_DATA" with 2 columns, COUNTRY and CONTINENT, and after that I added 3 records:

    Country         Continent
United States        America
Spain                 Europa
Germany               Europa

After that, I created a Range named RANGECOMBOBOX, and source is the Country column of my table. Check image:

You have to make sure this named range refers to the column of your table. In my case is just "=T_DATA[Country]".

After that, I Inserted the combobox and Right click on it, tab CONTROL, and I set the Entry Range as the named range I created before, in my case, RANGECOMBOBOX:

Third step is testing if the combobox get the values of the Country Column, and it does:

Now final test, I inserted 2 new records in my table (China and Japan values) and the combobox updates instantly, by just adding records to my table.

Hope this can give you a light in your task. Another option you have is doing the same I did but activate first the macro recorder and check the code. Maybe it can help you out with your issue.

UPDATED ANSWER:

Then try

Private Sub UserForm_Initialize()
Me.ClientNameComboxAdd.RowSource = "RangeCombobox"
End Sub

This worked on my userform, and the combobox loaded the countries. However, remember to unload and load again your form every time you insert new records into your table, to update the combobox



来源:https://stackoverflow.com/questions/48245937/using-rowsource-property-to-fill-combobox-in-excel-vba

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