Make your own free website on Tripod.com
Sort Numbered Items In List Box/Combo Box

If you place the items File1.gif, File2.gif, File3.gif and File10.gif in List Box or Combo Box, and set the Sorted property to True, they will come up listed this way:

File1.gif
File10.gif
File2.gif
File3.gif

Instead of this way:

File1.gif
File2.gif
File3.gif
File10.gif

The source code below show you how to sort them properly.
This example will sort List Box, but it's work exactly the same with Combo Box

Preparations

Add 1 Command Button and 1 List Box to your form.

Form Code

Sub ReSort(L As Control)
  Dim P%, PP%, C%, Pre$, S$, V&, NewPos%, CheckIt%
  Dim TempL$, TempItemData&, S1$
 
  For P = 0 To L.ListCount - 1
    S = L.List(P)
    For C = 1 To Len(S)
        V = Val(Mid$(S, C))
        If V > 0 Then Exit For
    Next
    If V > 0 Then
        If C > 1 Then Pre = Left$(S, C - 1)
        NewPos = -1
        For PP = P + 1 To L.ListCount - 1
            CheckIt = False
            S1 = L.List(PP)
            If Pre <> "" Then
                If InStr(S1, Pre) = 1 Then CheckIt = True
            Else
                If Val(S1) > 0 Then CheckIt = True
            End If
            If CheckIt Then
                If Val(Mid$(S1, C)) < V Then NewPos = PP
            Else
                Exit For
            End If
        Next
        If NewPos > -1 Then
            TempL = L.List(P)
            TempItemData = L.ItemData(P)
            L.RemoveItem (P)
            L.AddItem TempL, NewPos
            L.ItemData(L.NewIndex) = TempItemData
            P = P - 1
        End If
    End If
  Next
  Exit Sub
End Sub
 
Private Sub Command1_Click()
   Call ReSort(List1)
End Sub


Private Sub Form_Load()
'add items to the List Box
    List1.AddItem "File3.gif"
    List1.AddItem "File2.gif"
    List1.AddItem "File10.gif"
    List1.AddItem "File1.gif"
End Sub

Go Back