46

I have a table that can contain any number of rows:

enter image description here

As I said it can contain 1 or ∞ rows.

I want to sort range A3:D∞ by the Date cell that is in column B.
How can I do it?

The problem is that I don't know how to select from A3 to the last row.

I think that looping to the last row is not a correct method.

I have got this so far it sorts looks like correct, but the range is hard-coded.
How do I get rid of the hard-coding of the range?

Range("A3:D8").Sort key1:=Range("B3:B8"), _
order1:=xlAscending, Header:=xlNo

4 Answers 4

102

Try this code:

Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A3:D" & lastrow).Sort key1:=Range("B3:B" & lastrow), _
   order1:=xlAscending, Header:=xlNo
Sign up to request clarification or add additional context in comments.

3 Comments

Just a note: this doesn't work too well with datetimes data type, which are sorted as strings. Its safer to convert the fields to long and then sort.
It would be nice if this answer explained why the OP's code didn't work and then explains why this code given does work.
It is enough to specify any one cell in the column used for sorting and removes the need for dynamic tracking of number of rows for the key1 parameter. Range("A3:D" & lastrow).Sort key1:=Range("B4"), order1:=xlAscending, Header:=xlNo works here too
16

Or this:

Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
    Order1:=xlAscending, Header:=xlYes

2 Comments

I like this answer since it does not involve an additional variable
@sonyisda1 that's a bad reason, you could just replace the variable with the formula. But it is more clear what happens with the variable.
0

You can sort any range in a very dynamic way by using the SortRange and GetCurrentRegionStartingGivenCell function in Xatocode as follows:

' First you may define a worksheet level named range in cell "A2" and name it as rngData
Sub SortExample()

    Dim rngData         As Range ' Range to sort

    Set rngData = GetCurrentRegionStartingGivenCell(shtData.Range("rngData"))  
    Call SortRange(rngData, True, 2, xlAscending, 3, xlDescending)

End Sub

You can read the complete article here

Comments

-2

If the starting cell of the range and of the key is static, the solution can be very simple:

Range("A3").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Sort key1:=Range("B3", Range("B3").End(xlDown)), _
order1:=xlAscending, Header:=xlNo

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.