William C Johnson
asked on
How do I get an Excel 2007 sort macro to recognize variable columns and rows?
I recorded this macro. It fails to recognize variability when adding/deleting rows and columns. Although I have made this sheet into a table, it still does not recognize the variablity. Any suggestions on building a sort macro to account for a sheet or table sort with row and column variablity is appreciated. Attached is the spreadsheet. The macro is "Test".
ActiveWorkbook.Worksheets( "Attendanc e").ListOb jects("Att endance"). Sort. _
SortFields.Clear
ActiveWorkbook.Worksheets( "Attendanc e").ListOb jects("Att endance"). Sort. _
SortFields.Add Key:=ActiveCell.Offset(0, -21).Range("A1:A16"), SortOn:= _
xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets( "Attendanc e").ListOb jects("Att endance"). Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Test.xlsm
ActiveWorkbook.Worksheets(
SortFields.Clear
ActiveWorkbook.Worksheets(
SortFields.Add Key:=ActiveCell.Offset(0, -21).Range("A1:A16"), SortOn:= _
xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets(
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Test.xlsm
Renamed for your sheet...
lLastRow = ActiveWorkbook.Worksheets("Attendance").Cells(Rows.Count, 1).End(xlUp).Row
ActiveWorkbook.Worksheets("Attendance").ListObjects("Attendance").Sort. _
SortFields.Clear
ActiveWorkbook.Worksheets("Attendance").ListObjects("Attendance").Sort. _
SortFields.Add Key:=ActiveCell.Offset(0, -21).Range("A1:A" & lLastRow), SortOn:= _
xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Attendance").ListObjects("Attendance").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Glenn, your solution worked the best. Thank you for your help. I can now duplicate this functionality.
Open in new window