Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort cells in a column from A to Z?

Tags:

excel

vba

The code is from slightly edited macro. I tried to remove the 'messy code', however it is not working. The aim of it is to sort data in column BF from A to Z.

 Dim InSheet As Worksheet
    Set InSheet = ThisWorkbook.Worksheets("A to Z")
 Dim LastRow as Integer
   LastRow = InSheet.Cells(Rows.Count, 58).End(xlUp).Row

 InSheet.Select
     Columns("BF:BF").Select
 InSheet.Sort.SortFields.Clear
 InSheet.Sort.SortFields.Add Key:=Range( _
    "BF1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
  With InSheet.Sort
    .SetRange Range("A1:BF" & LastRow)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

SO I tried this and it is not working:

 Dim InSheet As Worksheet
    Set InSheet = ThisWorkbook.Worksheets("A to Z")
 Dim LastRow as Integer
   LastRow = InSheet.Cells(Rows.Count, 58).End(xlUp).Row

 InSheet.Columns("BF:BF")
 InSheet.Sort.SortFields.Clear
 InSheet.Sort.SortFields.Add Key:=Range( _
    "BF1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
  With InSheet.Sort
    .SetRange Range("A1:BF" & LastRow)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Any ideas? I would like to really avoid .select an other stuff as it is hugely decreasing performance.

like image 568
Petrik Avatar asked Dec 13 '25 11:12

Petrik


2 Answers

You can just directly sort the Range with a Key with out the rest of the code you have.

Range("A1:BF" & LastRow).SORT Key1:=Range("BF1"), Order1:=xlAscending_
        Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:= _
        xlTopToBottom, DataOption1:=xlSortNormal
like image 122
Steven Martin Avatar answered Dec 15 '25 03:12

Steven Martin


I used advice provided by both Steven Martin's answer and Dmitry Pavliv's comment, and this is working pretty well:

Dim InSheet As Worksheet
    Set InSheet = ThisWorkbook.Worksheets("A to Z")
    Dim LastRow As Integer
        LastRow = InSheet.Cells(Rows.Count, 58).End(xlUp).Row

With InSheet.Sort  ' sort data from A to Z
    .SetRange InSheet.Range("A1:BF" & LastRow)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With 
like image 33
Petrik Avatar answered Dec 15 '25 04:12

Petrik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!