Combo Box populated from a collection

R

Rob W

Greetings,

There is a popular piece of VBA code that is posted across forums and excel
site for populating controsl with unique values ONLY, it uses a collection
as apparently they dont allow duplicates.
By resuming the error when a duplicate value is detected you can form a
unique list.

I have pasted the code below.

I was wondering instead of populating the combo box in a For/Next loop per
Item, can I set the list value using the Collection in one go?

I had a few attempts without success (all syntax errors) e.g.
comboDiagnosis.List = Uniques(Uniques.Count)


'Populate combo box with unique Diagnosis values
With comboDiagnosis

Dim Uniques As New Collection
Dim i As Integer, j As Integer
Dim Swap1, Swap2, Item

On Error Resume Next

For Each cell In wsData.Range("G2:G" &
lRowEnd).SpecialCells(xlCellTypeConstants, 2)
Uniques.Add cell.Value, CStr(cell.Value)
Next cell

'Resume normal error handling
On Error GoTo 0

For i = 1 To Uniques.Count - 1
For j = i + 1 To Uniques.Count
If Uniques(i) > Uniques(j) Then
Swap1 = Uniques(i)
Swap2 = Uniques(j)
Uniques.Add Swap1, before:=j
Uniques.Add Swap2, before:=i
Uniques.Remove i + 1
Uniques.Remove j + 1
End If
Next j
Next i

For Each Item In Uniques
comboDiagnosis.AddItem Item
Next Item
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top