Click here to Skip to main content
15,889,874 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an Excel workbook that has 12 sheets, one for each month. I list all my monthly bills and enter the due dates for each bill. I would like to sort the bills by the due date and then by account name. I would like for this macro to work on whichever sheet I am on. Any suggestions?

What I have tried:

VB.NET
Sub Sort()

Keyboard Shortcut: Ctrl+s
    Range("A2:H28").Select
    ActiveWorkbook.Worksheets("JUN16").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("JUN16").Sort.SortFields.Add Key:=Range("C2:C28"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    ActiveWorkbook.Worksheets("JUN16").Sort.SortFields.Add Key:=Range("A2:A28"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("JUN16").Sort
        .SetRange Range("A1:H28")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Range("A2").Select
End Sub
Posted
Updated 9-Jun-16 13:00pm

1 solution

You should try to replace all ActiveWorkbook.Worksheets("JUN16") with ActiveSheet.

Application.ActiveSheet Property (Excel)[^]
 
Share this answer
 
Comments
Member 10376725 13-Jun-16 15:52pm    
ppolymorphe.. I tried your suggestion, first I got an "Expected end of statement error" with the "[^]" highlighted. got rid of the "[^]" and then got a "Sub or Function not defined" error. In trying to 'second guess' the problem I put a '.' between the ActiveSheet and Property and now get a "Type mismatch" error. I have re-recorded the macro and with your changes it looks like this:
' Keyboard Shortcut: Ctrl+s
'
Range("A2:H35").Select
ActiveSheet.Application.ActiveSheet Property(Excel)[^].Sort.SortFields.Clear
ActiveSheet.Application.ActiveSheet Property(Excel)[^].Sort.SortFields.Add Key:=Range("C2:C35"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveSheet.Application.ActiveSheet Property(Excel)[^].Sort.SortFields.Add Key:=Range("A2:A35"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveSheet.Application.ActiveSheet Property(Excel)[^].Sort
.SetRange Range("A1:H35")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A1").Select
End Sub

What am I doing wrong?
Patrice T 13-Jun-16 17:53pm    
look a&gain at solution.
second line is a link, not the same color as line 1
try
Range("A2:H35").Select
ActiveSheet.Sort.SortFields.Clear
...
Member 10376725 13-Jun-16 18:29pm    
DUH... how embarrassing... Thanks ppolymorphe works perfect when ya do it right...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900