Best code to sort a table column in a VBA macro

JenniferMurphy

Well-known Member
Joined
Jul 23, 2011
Messages
2,676
Office Version
  1. 365
Platform
  1. Windows
I am working on a macro that will do some processing on the data in a table. When it is done, it might want to sort the table on one column. Having no idea how to do that, I recorded 3 macros with different portions of the table column selected.

This was my first try. I selected one cell in the column.
VBA Code:
Sub Macro1()

' Recorded with one cell in column selected

    Range("D15").Select
    ActiveWorkbook.Worksheets("Example").ListObjects("TblExample").Sort.SortFields. _
        Clear
    ActiveWorkbook.Worksheets("Example").ListObjects("TblExample").Sort.SortFields. _
        Add2 Key:=Range("D15:D22"), SortOn:=xlSortOnValues, Order:=xlDescending, _
        DataOption:=xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("Example").ListObjects("TblExample").Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

This was my second try. I selected the column header.
Code:
Sub Macro2()

' Recorded with column header selected

    Range("TblExample[[#Headers],[WtdRtg]]").Select
    ActiveWorkbook.Worksheets("Example").ListObjects("TblExample").Sort.SortFields. _
        Clear
    ActiveWorkbook.Worksheets("Example").ListObjects("TblExample").Sort.SortFields. _
        Add2 Key:=Range("TblExample[[#Headers],[#Data],[WtdRtg]]"), SortOn:= _
        xlSortOnValues, Order:=xlDescending, DataOption:=xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("Example").ListObjects("TblExample").Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

This was my third try. I selected the entire column, but not the header. This looks like the best option. But do I need all of that code?
Code:
Sub Macro3()

' Recorded with entire column (without header) selected

    Range("TblExample[WtdRtg]").Select
    ActiveWorkbook.Worksheets("Example").ListObjects("TblExample").Sort.SortFields. _
        Clear
    ActiveWorkbook.Worksheets("Example").ListObjects("TblExample").Sort.SortFields. _
        Add2 Key:=Range("TblExample[WtdRtg]"), SortOn:=xlSortOnValues, Order:= _
        xlDescending, DataOption:=xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("Example").ListObjects("TblExample").Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Thanks for any help.
 
Thanks Jennifer, and Doh! - typo on the table header name in my code!
Rich (BB code):
.SortFields.Add Key:=Worksheets("Example").Range("TblExample[WtgRtg]"), Order:=2

Please try the amended code below:
VBA Code:
Sub JMurph2()
    With Worksheets("Example").ListObjects("TblExample").Sort
        .SortFields.Clear
        .SortFields.Add Key:=Worksheets("Example").Range("TblExample[WtdRtg]"), Order:=2
        .Header = xlYes
        .Apply
    End With
End Sub
 
Upvote 0

Excel Facts

Select all contiguous cells
Pressing Ctrl+* (asterisk) will select the "current region" - all contiguous cells in all directions.
Thanks Jennifer - although at least you've got an excuse - I think it's close to 2:00 am where you are :ROFLMAO:
 
Upvote 0
FWIW, since you refer to the same table twice in the code, I'd suggest assigning it to a variable so you only need to change it in one place if/when needed.
 
Upvote 0
FWIW, since you refer to the same table twice in the code, I'd suggest assigning it to a variable so you only need to change it in one place if/when needed.
What type of variable? Can you post the assignment code?
 
Upvote 0
A ListObject:

VBA Code:
Sub JMurph2()
dim lo as listobject: set lo = Worksheets("Example").ListObjects("TblExample")
    With lo.Sort
        .SortFields.Clear
        .SortFields.Add Key:=lo.listcolumns("WtdRtg").Range, Order:=2
        .Header = xlYes
        .Apply
    End With
End Sub
 
Upvote 0
A ListObject:

VBA Code:
Sub JMurph2()
dim lo as listobject: set lo = Worksheets("Example").ListObjects("TblExample")
    With lo.Sort
        .SortFields.Clear
        .SortFields.Add Key:=lo.listcolumns("WtdRtg").Range, Order:=2
        .Header = xlYes
        .Apply
    End With
End Sub

I tried to adapt your code to make use of my variable names, but I've done something wrong. My code is getting this error.

1685444873627.png


Here's my code. The error is on the .sortfields statement at the bottom.
VBA Code:
' Named range and derivative variables
Const rnDataTableName As String = "TableName"   'Cell containing the name of the table
  Dim rnTable As String                           'The name of the table
  Dim loTable As ListObject                       'The table as a list object

 . . .
 
' Call my IsATable UDF to check that the name is for a table
If Not IsATable(rnTable) Then Exit Function

' Define a ListObject variable. It will replace ActiveSheet.ListObject in the rest of the code
  On Error GoTo BadTableName      'Handle bad table names
  Set loTable = Range(rnTable).ListObject 'Load the list object
  On Error GoTo 0                         'Resume normal error handling
  GoTo TableNameOK                        'Resume processing
BadTableName:
  ErrMsg "Invalid table name (" & rnTable & ")": Exit Function:
TableNameOK:

' Load the table headers into one array and the body into another
aTblHdr = loTable.HeaderRowRange.Value2  'Load the table header row
aTblDat = loTable.DataBodyRange.Value2   'Load the table body

 . . .
 
' Write out just the weighted ratings column (2) of the array
loTable.ListColumns(aTblHdr(1, iWtdRtgCol)).DataBodyRange.Resize(UBound(aTblDat, 1)) _
       = Application.index(aTblDat, 0, iWtdRtgCol)

'Sort the table on the WtdRtg column
With loTable
  .SortFields.Clear   'This statement gets the error message
  .SortFields.Add Key:=loTable.ListColumns(sHdrWtdRtg).Range, Order:=2
  .Header = xlYes
  .Apply
End With

What am I doing wrong?

Thanks
 
Upvote 0

Forum statistics

Threads
1,223,244
Messages
6,170,976
Members
452,372
Latest member
Natalie18

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top