Link to home
Start Free TrialLog in
Avatar of Sylvania
SylvaniaFlag for Canada

asked on

Combo Sort

How can I sort NUMBERS in a combobox?
I'm using .sort method, but it sort the numbers as they were strings:
1
10
100
2
20
200
Thanks for your help.
Direct help would be appreciated rather then long workarounds, but I want to hear what you have to say.
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Can't you sort them before putting them in your combo?
Avatar of Sage020999
Sage020999

If you choose not to sort them before putting them in the combo box, you may need to pad the numbers with zeros. Some thing like this would work if you don't mind the extra digits:



Function Pad(ByVal Item As String) As String

    If IsNumeric(Item) Then
   
      If InStr(Item, ".") <> 0 Then
          Do Until InStr(Item, ".") = 10
              Item = "0" & Item
          Loop
      Else
          Do Until Len(Item) >= 9
            Item = "0" & Item
          Loop
      End If
 
    End If

 
  Pad = Item
 
End Function
ASKER CERTIFIED SOLUTION
Avatar of nico5038
nico5038
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Use this function to make your numbers proportional

Function Pad(ByVal Item As String) As String

    If IsNumeric(Item) Then
   
      If InStr(Item, ".") <> 0 Then
          Do Until InStr(Item, ".") = 10
              Item = " " & Item
          Loop
      Else
          Do Until Len(Item) >= 9
            Item = " " & Item
          Loop
      End If
   
    End If

   
  Pad = Item
   
End Function
Saga, proportionality isn't a property of a string and not of a number.
It has to do with a font. (The width of every single character can be different. A "m" is wide and a "i" is small)

When typing this comment the characters are NOT proportional. When viewing the result it's proportional!

Just copy and paste my sample in the input window and you can see the numbers are all right-aligned!
heres a sort algorithm i wrote real quick.  Not super proficient but it gets the job done.


Option Explicit
Dim arr() As Integer

Private Sub Form_Load()
    Dim i As Integer
    ReDim arr(0 To Combo1.ListCount - 1)
    For i = 0 To Combo1.ListCount - 1
        arr(i) = Combo1.List(i)
    Next
    Call SortBox(arr)
End Sub


Function SortBox(tArr As Variant)
    Dim i As Integer
    Dim j As Integer
    Dim temp As Integer
    For i = 0 To UBound(arr)
        For j = i + 1 To UBound(arr)
            If tArr(j) < tArr(i) Then
                temp = tArr(i)
                tArr(i) = tArr(j)
                tArr(j) = temp
            End If
        Next
    Next
    Combo1.Clear
    For i = 0 To UBound(tArr)
        Combo1.AddItem tArr(i)
    Next
End Function