'VBA - How to sort values in listbox in ascending order?
I am looking for a way to sort items in my userform listbox. So far I have the code below:
Dim i As Long
Dim j As Long
Dim Temp As Variant
With ListBoxName
For i = 0 To .ListCount - 2
For j = i + 1 To .ListCount - 1
If .List(i) > .List(j) Then
Temp = .List(j)
.List(j) = .List(i)
.List(i) = Temp
End If
Next j
Next i
End With
This code works but sadly, it does not sort the numbers properly. I want to sort the numbers the following way: 1,2,3,4,5,6,7,8,9,10,11,12,13,14
but my code sorts these number like this: 1,10,11,12,13,14,2,3,4,5,6,7,8,9
How can I sort items in listbox numerically in ascending order? I populate the listbox using ListBoxName.AddItem
command. What am I doing wrong?
Solution 1:[1]
If you need to sort a listbox with multiple columns:
Sub SortListbox(LBX As msforms.ListBox, Col As Integer)
DisableEventiUF = True
Dim i As Long
Dim j As Long
Dim Temp As Variant
Dim Y As Integer
With LBX
For i = 0 To .ListCount - 2
For j = i + 1 To .ListCount - 1
If .List(i, Col) >= .List(j, Col) Then
For Y = 0 To .ColumnCount - 1
Temp = .List(j, Y)
.List(j, Y) = .List(i, Y)
.List(i, Y) = Temp
Next Y
End If
Next j
Next i
End With
DisableEventiUF = False
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daniele Marotta |