Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Excel sort range by specific column

Tags:

sorting

excel

vba

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 
like image 805
Cheese Avatar asked Jan 30 '14 08:01

Cheese


2 Answers

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 
like image 137
Dmitry Pavliv Avatar answered Sep 28 '22 05:09

Dmitry Pavliv


Or this:

Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _     Order1:=xlAscending, Header:=xlYes 
like image 33
L42 Avatar answered Sep 28 '22 04:09

L42