42

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
Teamothy
  • 1,990
  • 3
  • 13
  • 20
Cheese
  • 4,164
  • 5
  • 32
  • 59

3 Answers3

96

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
Dmitry Pavliv
  • 34,697
  • 12
  • 76
  • 78
  • 2
    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. – Yasskier Nov 15 '15 at 20:22
15

Or this:

Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
    Order1:=xlAscending, Header:=xlYes
L42
  • 18,912
  • 11
  • 41
  • 65
  • I like this answer since it does not involve an additional variable – sonyisda1 Sep 02 '16 at 14:31
  • 7
    @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. – Kami Kaze Feb 23 '17 at 13:52
-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
Simi
  • 5
  • 1
  • 12
    [How to avoid using Select in Excel VBA](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros) – Wolfie Aug 29 '17 at 11:42