Log in

View Full Version : Populate a combo or list box with variables?



mud2
10-02-2008, 11:05 AM
So, can I populate a box with variables? I.e, a function that returns a name(s) that should be used as the choices?
Example: An Array ATAble() The box values would be ATable(i) with i from some start to some finish.....
Randy???

CreganTur
10-02-2008, 11:55 AM
Here's an example for you- you need to create a new form with a listbox named ListTest and add a button named btnPopulate. Put the following code behind the button's click event:


Dim arrTest(5)
Dim i As Integer
Dim strList As String
arrTest(0) = "ninja"
arrTest(1) = "pirate"
arrTest(2) = "samurai"
arrTest(3) = "foo"
arrTest(4) = "poo"
For i = 0 To UBound(arrTest)
strList = strList & arrTest(i) & ";"
Next
Me.ListTest.RowSourceType = "Value List"
Me.ListTest.RowSource = strList



As you can see, first we iterate through your array, delimiting every value with a semicolon- this is necessary since a semicolon is what causes different values in a Value List to show on seperate lines in the listbox. I start with i = 0 because Access starts its numbering sequences at zero (0), unless you use Option Base 1, which starts the numbering at 1. Next I use the UBound function- this gets the number of the upper bound, the very last member in an array. That way if your array is dynamic, you don't have to worry about explicitly declaring where your array ends.

Next we just set the properties for your listbox via VBA, and populate it with the list we created.

HTH:thumb