A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
Here is a _Deactivate() routine that will sort the sheet just deactivated and two others that perhaps you can use as a model. It's pretty fast - sorting 1000 rows with columns A:I sorted on 2 of them, and A:F sorted on the 3rd one.
And here is a web page showing how to add code to a worksheet's code module:
http://www.contextures.com/xlvba01.html#Worksheet
NOTE: these sort routines only work in Excel 2007/2010, they will fail in 2003 and earlier as sorting setup in them was different. If you need code to use in 2003 also (which would also work in 2007/2010), let me know.
Private Sub Worksheet_Deactivate()
Const FirstSortCol = "A"
Const LastSortCol = "I"
Const S3_LastSortCol = "F" ' see below
Const SortKeyCol = "A"
Const FirstDataRow = 2 ' assumes labels in row 1
Dim anyWS As Worksheet
Dim lastRow As Long
'first we sort the sheet just deactivated
Set anyWS = Me
lastRow = anyWS.Range(SortKeyCol & Rows.Count).End(xlUp).Row
anyWS.Sort.SortFields.Clear
anyWS.Sort.SortFields.Add Key:=Range(SortKeyCol & 1), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortTextAsNumbers
With anyWS.Sort
.SetRange Range(FirstSortCol & FirstDataRow _
& ":" & LastSortCol & lastRow)
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'
'now we go on to sort another sheet
Set anyWS = Worksheets("Sheet2")
'assumes it is set up just like the first one
anyWS.Sort.SortFields.Clear
anyWS.Sort.SortFields.Add Key:=Range(SortKeyCol & 1), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortTextAsNumbers
With anyWS.Sort
.SetRange Range(FirstSortCol & FirstDataRow _
& ":" & LastSortCol & lastRow)
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'now a 3rd sheet, but set up slightly
'differently, only want to sort columns A:F, not A:I
'so we use S3_LastSortCol in this instead of LastSortCol
Set anyWS = Worksheets("Sheet3")
anyWS.Sort.SortFields.Clear
anyWS.Sort.SortFields.Add Key:=Range(SortKeyCol & 1), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortTextAsNumbers
With anyWS.Sort
.SetRange Range(FirstSortCol & FirstDataRow _
& ":" & S3_LastSortCol & lastRow)
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'some housekeeping cleanup
Set anyWS = Nothing
End Sub