简体   繁体   中英

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?

Try, please replacing of

If .List(i) > .List(j) Then

with

If CLng(.List(i)) > CLng(.List(j)) Then 

and change:

Temp = CLng(.List(j)) 

In this way, the comparison it is done between numbers, not between strings.

But if you have also strings in the list box, the code will return an error...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM