Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

populate combobox in VBA with array elements

I have a VBA procedure (in Excel 2007) where I aspire to set the ListFillRange property of a combobox styled as a list using an array.

I know this works if I right click the combobox and write "Sheet1!$F2:$F17" next to the "ListFillRange" property. I can also do this in code. However, I am interested in dynamically setting the value of this property by assigning it an array.

I know for sure the array works as I tested it; there is probably a syntax error here:

ThisWorkbook.Worksheets("Sheet1").OLEObjects("cmbS").ListFillRange = ar

when I do this I get: "Type mismatch" error.

The result of this action should be that the component is populated with the array elements, from element(0) ... to the last element (n-1) of the array. Any pointers, thank you very much!

I also tried:

ThisWorkbook.Worksheets("Sheet1").cmbS.list = ar

and it says "permission denied"

Here are the combobox properties in case it helps: enter image description here

After testing and trying, I found this works:

ThisWorkbook.Worksheets("Sheet1").cmbS.ListFillRange = ""

Dim i As Integer
For i = LBound(ar) To UBound(ar)
    ThisWorkbook.Worksheets("Sheet1").cmbS.AddItem (ar(i))

Next

However, I am interested in populating with all values at once for faster effect, not just adding element by element.

like image 657
Sam Avatar asked Mar 14 '13 16:03

Sam


People also ask

How do I populate a ComboBox in VBA?

One way to add multiple values to your ComboBox is to use the ComboBox List property, or . List . To use the ComboBox . List property, you simply need to put your dropdown menu options into an array and separate each dropdown item by a comma.

How do I add data to a ComboBox in VBA?

Go to the VBA window (Alt + F11) > double-click the UserForm from the Project window (Ctrl + R if it's not visible) and then, once the form is visible, click the ComboBox that you want to fill with values. Look to the Properties window and scroll down to RowSource. If the Property window isn't visible, hit F4.


1 Answers

I know its late but maybe it is going to help someone else. At least the following code works (much faster than element for element) for me.

dim arr() as variant

arr = Worksheets("Total").Range("C2:"&lrow).Value
Worksheets("Menu").ComboBox2.List = arr
like image 127
olr Avatar answered Sep 28 '22 02:09

olr