Excel VBA Sorting Problem

Closed
Hassan - Sep 27, 2019 at 12:29 PM
vcoolio Posts 1411 Registration date Thursday July 24, 2014 Status Moderator Last seen September 6, 2024 - Sep 29, 2019 at 10:02 PM
Hello,
This code is placing all the header names in the last row after sorting in descending order. Can you please help how to keep the position of column names fixed?
Related:

1 response

vcoolio Posts 1411 Registration date Thursday July 24, 2014 Status Moderator Last seen September 6, 2024 262
Sep 29, 2019 at 06:52 AM
Hello Hassan,

You haven't supplied the code so its a little difficult to determine what the problem is.

Please try again.

Cheerio,
vcoolio.
0
Thanks for your response. I want to use the code below to sort my columns by searching for columns header first, but the problem is that my headers are in the second row of the sheet and not the first row. Therefore, Header:= xlYes will not work as it will only work for the headers in 1st row. Can you please edit the code below so that I can get the headers to be read in the second column. This will solve my problem as headers will remain fixed and the rest of the data will be sorted in descending order. Thank you so much.

Sub sorting()
Dim col As String, cfind As Range
Worksheets(1).Activate
col = "sku"
Set cfind = Cells.Find(what:=col, lookat:=xlWhole)
ActiveSheet.Cells.Sort key1:=cfind, Header:=xlYes
End Sub
0
vcoolio Posts 1411 Registration date Thursday July 24, 2014 Status Moderator Last seen September 6, 2024 262
Sep 29, 2019 at 10:02 PM
Hello Hassan,

I want to use the code below to sort my columns by searching for columns header first

I'm assuming then that your "SKU" column will never be in the same place (it could be Column C or Column F or Column Z etc.) so try the code amended as follows:-


Sub Sorting()

    Dim acell As Range
    Set acell = Rows(2).Find(What:="sku", LookIn:=xlValues, LookAt:=xlWhole)

ActiveSheet.Range("A2").Sort acell.Offset(1), 2, Header:=xlYes

End Sub


I'm also assuming that your data starts in Column A, Row3.

The code above should sort your data descending.

I hope that this helps.

Cheerio,
vcoolio.
0