dynamic sheetnames in macro

kendel

Board Regular
Joined
Mar 2, 2010
Messages
133
Hello, I want to be able to run this sort on any sheet in the workbook. I used the recorder to get this but don't know how to make it dynamic, it only works on sheet m2b (2). What do I change '.Worksheets("m2b (2)")' to? Is there a way to not refer to the sheet at all?

ActiveWorkbook.Worksheets("m2b (2)").sort.SortFields.Clear
ActiveWorkbook.Worksheets("m2b (2)").sort.SortFields.Add Key:=ActiveCell. _
Range("A1:D1"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("m2b (2)").sort
.SetRange ActiveCell.Range("A1:D1")
.Header = xlGuess
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply



Thanks,
Kendel, Excel 2007 & 2010
 

Excel Facts

How to calculate loan payments in Excel?
Use the PMT function: =PMT(5%/12,60,-25000) is for a $25,000 loan, 5% annual interest, 60 month loan.
Use the keyword ActiveSheet to reference the currently active sheet.

Code:
    With ActiveSheet.Sort
        .SortFields.Clear
        .SortFields.Add Key:=ActiveCell. _
                        Range("A1:D1"), SortOn:=xlSortOnValues, _
                        Order:=xlDescending, DataOption:=xlSortNormal
        .SetRange ActiveCell.Range("A1:D1")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlLeftToRight
        .SortMethod = xlPinYin
        .Apply
 
Upvote 0

Forum statistics

Threads
1,224,599
Messages
6,179,827
Members
452,946
Latest member
JoseDavid

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top