David Gard
David Gard

Reputation: 12047

Sorting an Excel list using VBA is not working

I'm trying to sort a series of lists alphabetically by a column called "Name". The below code is compliling without error, and running without error, but it is not sorting the lists.

Can anyone help at all?

'**
 ' Sorts the defined list using the definded parameters
 ''
Function sort_list(list_name As String, column_name As String, Optional sort_order As String = xlAscending)

Dim list As ListObject          ' The list that is to be sorted
Dim sort_column As Range        ' The column in the list that is to be used as the sort key

    ' Set the list and the sort column
    Set list = WS_ext.ListObjects(list_name)
    Set sort_column = list.ListColumns(column_name).Range

    ' Sort the list
    With list.Sort
        .SortFields.Clear
        .SortFields.Add sort_column, sort_order
        .Header = xlYes
        .MatchCase = False
        .Apply
    End With

End Function

Upvotes: 2

Views: 2886

Answers (1)

David Gard
David Gard

Reputation: 12047

The issue is that I didn't specify which arguments were which for the SortFields function. Changing that line to the below fixed my problem.

.SortFields.Add Key:=sort_column, order:=Sort_order

Upvotes: 2

Related Questions