Search code examples
excelvba

VBA case insensitive sorting within listbox


I have the code below which is used to remove duplicates and sort the values alphabetically into a listbox within a userform but it is prioritizing uppercase over alphabetical and I would like it to ignore the case of the text

    Dim Coll As Collection, cell As Range, LastRow As Long
    Dim blnUnsorted As Boolean, i As Integer, temp As Variant
    Dim SourceSheet As Worksheet
    Set SourceSheet = Worksheets("Groups")
    
    '///////////////////////////////////////////////////////
    
    'Populate the ListBox with unique Make items from column A.
    LastRow = SourceSheet.Cells(Rows.Count, 1).End(xlUp).Row
    On Error Resume Next
    Set Coll = New Collection
    'Open a With structure for the ListBox control.
    With ClientInput
        .Clear
        For Each cell In SourceSheet.Range("A2:A" & LastRow)
            'Only attempt to populate cells containing a text or value.
            If Len(cell.Value) <> 0 Then
                Err.Clear
                Coll.Add cell.Text, cell.Text
                If Err.Number = 0 Then .AddItem cell.Text
                End If
        Next cell
            blnUnsorted = True
            Do
            blnUnsorted = False
            For i = 0 To UBound(.List) - 1
                If .List(i) > .List(i + 1) Then
                    temp = .List(i)
                    .List(i) = .List(i + 1)
                    .List(i + 1) = temp
                    blnUnsorted = True
                    Exit For
                End If
            Next i
        Loop While blnUnsorted = True
    'Close the With structure for the ListBox control.
    End With

Current

AC

AZ

ab

Desired

ab

AC

AZ


Solution

  • Instead of

     If .List(i) > .List(i + 1) Then
    

    use

     If LCase(.List(i)) > LCase(.List(i + 1)) Then