Creating a variable cell reference in a 'sorting' macro

George Philp

New Member
Joined
Nov 28, 2013
Messages
5
Sub All()
'
' All Macro
'
' Keyboard Shortcut: Ctrl+z
'
Range("A6:Z23").Select
ActiveWorkbook.Worksheets("All").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("All").Sort.SortFields.Add Key:=Range("Z6:Z23"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("All").Sort.SortFields.Add Key:=Range("U6:U23"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("All").Sort
.SetRange Range("A6:Z23")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub

This macro sorts data in a spreadsheet, and whilst the ‘top left’ value is fixed (A6, Z6, and U6) the bottom right value (Z23 and U23) is variable dependent on the number of rows in the spreadsheet. I do have a cell which is a count of the number of rows to sort (18 in this spreadsheet). Is there any way that I can code this in the macro to save me from editing the macro if rows are added/deleted? It would in effect be (for example) “Z” concatenated with “5 plus this cell value”.
 
Last edited:

James006

Well-known Member
Joined
Apr 4, 2009
Messages
3,680
Hello,

You can a variable such as last

last = Worksheets("All").Cells(Rows.Count, 1).End(xlUp).Row

and then use it as follows:

Range("A6:Z"&last)

Hope this will help
 

George Philp

New Member
Joined
Nov 28, 2013
Messages
5
Hi James006.

Thank you so much for your speedy and helpful reply.

I am very much a novice in comparison to your obvious Excel skills! I'm afraid I can't follow your code, but the variable that I need 'last' to be will always be in cell AA1 on the 'All' sheet.

I have tried last = "All"!AA1 and a few other permutations, but no joy :(

Thanks in advance!
George
 

James006

Well-known Member
Joined
Apr 4, 2009
Messages
3,680
Hi,

With the variable last ... there is no need for cell AA1 to hold the total number of rows ...

Should you still want to use the contents of cell AA1 :

last = Worksheets("All").Range("AA1").Value

Hope this will help
 
Last edited:

Forum statistics

Threads
1,085,291
Messages
5,382,742
Members
401,802
Latest member
JodieInCanada

Some videos you may like

This Week's Hot Topics

Top