Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VB This Active Worksheet

I'm sure this is really easy but I can't find any info on it.

I've got a Excel macro which has things like:

    ActiveWorkbook.Worksheets("Data 21 Oct 12 11-05").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Data21 Oct 12 11-05").Sort.SortFields.Add Key _
    :=Range("W1:W23"), SortOn:=xlSortOnValues, Order:=xlDescending, _
    DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Data 21 Oct 12 11-05").Sort
    .SetRange Range("A1:BZ23")
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

What I want to do is make this a global macro but the file name is hard coded in the macro. How can I change the code so it references "this" currently open file?

like image 668
Dan Twining Avatar asked Oct 21 '12 10:10

Dan Twining


People also ask

How do you know which sheet is active in Excel?

In spreadsheet programs such as Excel or Google Spreadsheets, the active cell is identified by a colored border or outline surrounding the cell. The active cell is always in the active sheet.

How do you define an active workbook in VBA?

To activate a workbook using VBA, you need to use the Workbook. Activate method. In this method, you need to specify the workbook name using the Workbook object. It also allows you to use the workbook number instead of the workbook name, but you can only refer to the open workbooks.


2 Answers

Ok, I worked out you need to change it from:

ActiveWorkbook.Worksheets("Data 21 Oct 12 11-05").Sort.

to:

ActiveWorkbook.ActiveSheet.Sort

Credit to this SO item on creating a button in Excel

like image 139
Dan Twining Avatar answered Oct 31 '22 14:10

Dan Twining


ActiveWorkbook does reference the current open and active file.

If by file name you refer to the fact that the sheet name is hard coded, you can make the macro work with the active sheet by replacing ActiveWorkbook.Worksheets("Data 21 Oct 12 11-05") with ActiveSheet.

like image 29
assylias Avatar answered Oct 31 '22 12:10

assylias