View Single Post
 
Old 01-19-2015, 02:08 PM
darbybrown darbybrown is offline Windows 8 Office 2010 32bit
Novice
 
Join Date: Jan 2015
Posts: 4
darbybrown is on a distinguished road
Default One macro to sort individual sheets in a workbook

I have a workbook of 12 sheets, one for each calendar month. The sheets are identical as far as rows and columns are concerned, and the data types in each column are the same in each sheet. I want to write one macro that will sort the data on the sheet that is open at the time. Below is the macro generated through Excel followed by the macro as I have changed it. Needless to say if it worked I wouldn't be asking for help. I get an error '13' "Type Mismatch" the very first line where I use the variable 'sheet'. If I try to dimension sheet as a String I get a compiler error. It's probably a simple thing that I can't see but any help would be appreciated.

Generated Macro code:

Sub Sort_Sheet()
'
' Sort_Sheet Macro
' Sorts data on Due Date and then on Account.
'
' Keyboard Shortcut: Ctrl+s
'
Range("A1:H35").Select
ActiveWorkbook.Worksheets("JAN15").Sort.SortFields .Clear
ActiveWorkbook.Worksheets("JAN15").Sort.SortFields .Add Key:=Range("C2:C35"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("JAN15").Sort.SortFields .Add Key:=Range("A2:A35"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("JAN15").Sort
.SetRange Range("A1:H35")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A2").Select
End Sub


My changes:

'Sub Sort_Sheet()
'
' Sort_Sheet Macro
' Sorts data on Due Date and then on Account.
'
' Keyboard Shortcut: Ctrl+s
'
Dim sheet As Worksheet

Range("A1:H35").Select
ActiveWorkbook.Worksheets(sheet).Sort.SortFields.C lear
ActiveWorkbook.Worksheets(sheet).Sort.SortFields.A dd Key:=Range("C2:C35"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets(sheet).Sort.SortFields.A dd Key:=Range("A2:A35"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets(sheet).Sort
.SetRange Range("A1:H35")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A2").Select
End Sub
Reply With Quote