
02-19-2007, 12:23 PM
|
|
Contributor
* Expert *
|
|
Join Date: Dec 2001
Posts: 725
|
|
Hello!
I took the following code from the link below and adapted it for your problem:
http://www.dailydoseofexcel.com/arch...ing-listboxes/
The list should display A - D even though the values were added in a different order.
Code:
Private Sub UserForm_Initialize()
Dim vaItems As Variant
Dim i As Long, j As Long
Dim vTemp As Variant
Me.ListBox1.AddItem "B"
Me.ListBox1.AddItem "A"
Me.ListBox1.AddItem "D"
Me.ListBox1.AddItem "C"
'Put the items in a variant array
vaItems = Me.ListBox1.List
'Steal code from John Walkenbach’s Excel Power Programming
'with VBA to sort the array
For i = LBound(vaItems, 1) To UBound(vaItems, 1) - 1
For j = i + 1 To UBound(vaItems, 1)
If vaItems(i, 0) > vaItems(j, 0) Then
vTemp = vaItems(i, 0)
vaItems(i, 0) = vaItems(j, 0)
vaItems(j, 0) = vTemp
End If
Next j
Next i
'Clear the listbox
Me.ListBox1.Clear
'Add the sorted array back to the listbox
For i = LBound(vaItems, 1) To UBound(vaItems, 1)
Me.ListBox1.AddItem vaItems(i, 0)
Next i
End Sub
Let us know if this helps!
~Mike
p.s. Please change the ListBox name if it is not "ListBox1". Thanks!
|
|