Поиск

Сортировка ComboBox или ListBox


Public Sub SortListBox(ByRef LB As MSForms.ComboBox) ' Можно по менять на MSForms.ListBox

    Dim First As Integer
    Dim Last As Integer
    Dim NumItems As Integer
    Dim i As Integer
    Dim j As Integer
    Dim Temp As String
    Dim TempArray() As Variant
    
    ReDim TempArray(LB.ListCount)
    
    First = LBound(TempArray)               ' this works correctly
    Last = UBound(TempArray) - 1            ' this works correctly
    
    For i = First To Last
        TempArray(i) = LB.List(i)           ' this works correctly
    Next i
    
    For i = First To Last
        For j = i + 1 To Last
            If Val(TempArray(i)) > Val(TempArray(j)) Then
                Temp = TempArray(j)
                TempArray(j) = TempArray(i)
                TempArray(i) = Temp
            End If
        Next j
    Next i
    
    LB.Clear
    
    For i = First To Last
        LB.AddItem TempArray(i)
    Next i

End Sub