Search code examples
vbasortingexcelworksheet-function

Sorting Worksheet data by column values using Excel VBA


I have next userform developed in vba, which takes info from a worksheet for displaying info

enter image description here

I want to order all the info aphabetically by a Segment, this is the code:

Function llenarDatosTabla()

    Dim vList As Variant
    Dim ws As Worksheet: Set ws = Worksheets(BD_PRODXSIST)

    ListBox1.Clear

    With ws
        If (IsEmpty(.Range("AA2").Value) = False) Then

            Dim ultimoRenglon As Long: ultimoRenglon = devolverUltimoRenglonDeColumna("A1", BD_PRODXSIST)

            vList = ws.Range("AA2:AA" & ultimoRenglon & ":AL2").Value

            If IsArray(vList) Then
                Me.ListBox1.List = vList
            Else
                Me.ListBox1.AddItem (vList)
            End If

        End If

        Me.ListBox1.ListIndex = -1

    End With




    Set vList = Nothing
    Set ws = Nothing
End Function

how to make it ordered by 'AD' (SEGMENTO) column???


Solution

  • You can sort your Excel Worksheet in ascending order using VBA statement like the following:

    Columns("A:XFD").Sort key1:=Range("AD:AD"), order1:=xlAscending, Header:=xlYes
    

    Note: in the column range Columns("A:XFD") instead of XFD enter the last used column pertinent to your case, e.g. Columns("A:DD").

    Hope this will help.