PDA

View Full Version : populate combobox using array



bilo11
03-18-2011, 04:15 PM
Hello everybody

I am currently working on a system for teachers in my department to select their teching group and a unit of work so that they can export some files that are linked to from a spreadsheet.

The problem is that the classes change every year and I want to update a combobox dynamically by checking the classes and only adding one if it is not already in the combobox. I have opted to use an array to store the classes before adding them to the combobox.

The code is below, but it only adds one group and the rest are left out. Does anybody have any suggestions?

Thanks very much

Dim tempGroup As String
Dim inc As Integer
Dim n As Integer
Dim doesContain As Boolean
Dim groups() As String
Dim nextItem As Integer
Dim groupLimit As Integer

ComboBox1.Clear

inc = 6
groupLimit = 0


Do Until Sheets("Results").Cells(inc, 2).Value = ""
tempGroup = Sheets("Results").Cells(inc, 3).Value
doesContain = False
n = 0
ReDim groups(groupLimit)
Do Until n = UBound(groups)
If groups(n) = tempGroup Then
doesContain = True
groupLimit = groupLimit + 1
Exit Do
End If
n = n + 1
Loop

If doesContain = False Then
groups(groupLimit) = tempGroup
End If
inc = inc + 1
Loop
Dim x As Integer ' x is the incrementor for adding items to the combobox
For x = 0 To UBound(groups)
ComboBox1.AddItem (groups(x))
Next

mdmackillop
03-18-2011, 04:45 PM
Have a look at this KB Item (http://www.vbaexpress.com/kb/getarticle.php?kb_id=824). The Range can be set either in the code or by using a dynamic range name.