6

I have tried to sort a table using the following VBA code. The code does select the correct column, and the column filter does get a small arrow in it, indicating that it is sorted. But the rows do not sort. They stay unsorted.

What is wrong?

Sub SortTableTest()
    Dim tbl As ListObject
    Dim columnToSortBy As Range

    Set tbl = Sheets("PB").ListObjects("AI")
    Set columnToSortBy = tbl.ListColumns(9).Range

    'Sort table
    With tbl.Sort
        .SortFields.Clear
        .SortFields.Add columnToSortBy, xlDescending
        .Header = xlYes
        .MatchCase = False
        .Apply
    End With
End Sub
2
  • Additionally, if you know how I can reference the column I am interested in by name instead of by column, that would be great. Commented Oct 22, 2013 at 8:36
  • Since table is often a misnomer in Excel a lot of people are likely looking for how to sort data in general: Sort data based on column Commented Feb 12, 2024 at 15:58

1 Answer 1

5

First, you missed one parameter in .SortFields.Add method. What you need is:

.SortFields.Add columnToSortBy, xlSortOnValues, xlDescending

Second, question from you comment. Try with this kind of References:

Set columnToSortBy = Range(tbl.Name & "[[#All],[column name here]]")
Sign up to request clarification or add additional context in comments.

2 Comments

When I use Range as mentioned above, I get the error method 'Range' of object _Global failed? I know, this is Avery old thread...may be somebody could help me?
@Venu, you should somehow show your code. Best idea is to post your own question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.