Sort Data rows by column B value

User avatar
adam
SilverLounger
Posts: 2347
Joined: 23 Feb 2010, 12:07

Sort Data rows by column B value

Post by adam »

Hi anyone,

The following code sorts data rows in ascending manner by the date in column A. How could I make the code to sort data rows by column value in B instead of column A. Meaning I have serial numbers in the custom format 0001 and so on.

Code: Select all

Sub SortSerial()
    Dim c As Integer
    With Sheets("OrderData").Range("A1").CurrentRegion
        c = .Find(What:="Date", After:=.Cells(1, 1), LookIn:=xlFormulas, _
            LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False).Column
            .Sort Key1:=.Cells(1, c), Order1:=xlAscending, Header:=xlYes, _
            OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
    End With
End Sub
My column headers are in row 4 and my data rows start from row 5 from column A to I.

Any help on this would be kindly appreciated.

Thanks in advance.
Best Regards,
Adam

User avatar
HansV
Administrator
Posts: 78531
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Sort Data rows by column B value

Post by HansV »

The code that you posted does not sort by column A as you can easily see by reading it.
Best wishes,
Hans

User avatar
adam
SilverLounger
Posts: 2347
Joined: 23 Feb 2010, 12:07

Re: Sort Data rows by column B value

Post by adam »

How about this version?

Code: Select all

Sub SortbySerial()
    Dim c As Integer
    With Sheets("OrderData").Range("B4").CurrentRegion
        c = .Find(What:="Serials", After:=.Cells(1, 1), LookIn:=xlFormulas, _
            LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False).Column
            .Sort Key1:=.Cells(1, c), Order1:=xlAscending, Header:=xlYes, _
            OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
    End With
End Sub
In column B row 4 I have heading Serials. Is this sorting the rows by column B?
Best Regards,
Adam

User avatar
HansV
Administrator
Posts: 78531
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Sort Data rows by column B value

Post by HansV »

If you want to sort on column B, you don't need the Find method at all.
Best wishes,
Hans

User avatar
adam
SilverLounger
Posts: 2347
Joined: 23 Feb 2010, 12:07

Re: Sort Data rows by column B value

Post by adam »

So what do I have to do? I would be happy if you let me know how to do that.

Thanks in advance.
Best Regards,
Adam

User avatar
adam
SilverLounger
Posts: 2347
Joined: 23 Feb 2010, 12:07

Re: Sort Data rows by column B value

Post by adam »

Nevermind. I've got it solved.
Best Regards,
Adam