I need Excel to detect the last column I have and sort on that column. I have a macro that generates a new column every time it is used so I cannot use a constant.
Sub sortyness()
Dim sortdata(A1 & ":", Cells(LastRow, LastColumn)) As Range
ActiveWorkbook.Worksheets("Compiled").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Compiled").Sort.SortFields.Add _
Key:=Range(Sorton), Sorton:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Compiled").Sort
.SetRange Range(sortdata)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Here's a screenshot of the sheet:
I am having trouble with getting it to sort by the last column. Can I define the column by looking for the first cell in row 1 that has no data and then use that as a basis to sort? How should I modify my VBA?
Thank you.
I don't know how to edit this thing to get it to not appear as a duplicate, but it's obviously not a duplicate. Mine is more concerned with running a macro on the last column than it is finding the last column.
Sort the "last" column with a single line of VBA:
...which is exactly the same as:
An vba sort operation actually requires much less code than you get from a recording.
Concerning the second line here:
This is not how you assign range. If you want to assign a range, starting on
A1
and ending onlastRow, lastColumn
, consider this:In the above case the range is assigned to the
ActiveSheet
, which is not always what you may need. If you want to avoid assigning to theActiveSheet
, you should specify the worksheet as well:The two dots in the code above
.Range
and.Cells
will make sure that you refer to theWorksheets("Compiled")
and thus will save some problems in the future.