Sorting a range on specific column of data using VBA in Excel

In my previous post I imported a CSV file into my spreadsheet and displayed the rows after my headings row. I now want to sort the rows by a column of data, but I do not want the heading to be part of the sort, so I basically want to sort the rows based upon the column starting at the row below the column headings – I hope that makes sense.

Anyway, we’re going to need to find all the rows and columns that make our range of data and then select a slice of the data which are our value items to sort. Here’s the code

rows = ws.Cells(Rows.Count, "A").End(xlUp).Row
columns = ws.Cells(3, Columns.Count).End(xlToLeft).Column
    
Set dataRange = ws.Range(Cells(3, 1), Cells(rows, columns))
Set sortColumn = ws.Range(Cells(3, 5), Cells(rows, 5))
dataRange.Sort key1:=sortColumn, order1:=xlDescending

In this example we set rows to be the row count and columns to be the number of columns starting at row 3 (where our data is imported to). Next we turn these values into a range object (mine’s named dataRange) again using row 3 as our data’s starting point. Next we create a sortColumn range to be the actual column we want to use as our sort key, in this case I’m using column 5 data. Finally we sort the first data range using the second and mine sort is descending in this example.