Home Why isn't my VBA sorting my column data correctly?
Reply: 1

Why isn't my VBA sorting my column data correctly?

SenthamilVM
1#
SenthamilVM Published in 2018-02-14 14:08:40Z

I am trying to delete the first row of the Excel sheet and sort a specific column using its name "CUST_RELPO". I am using the column header name since the name may change.

Sorting and copying the column from the second row since I do need to copy the column header.

Sub ClearFirstRow()
'
' ClearFirstRow Macro
'

'
Rows("1:1").Select
    Selection.Delete Shift:=xlUp
    Cells.Select
  Dim rngcustrelpo As Range
  xindex = Application.ActiveCell.Column
  Set rngcustrelpo = ActiveSheet.UsedRange.Find("CUST_RELPO")
  If rngcustrelpo Is Nothing Then
    MsgBox "CUST_RELPO column was not found."
    Exit Sub
    End If
    'Cells.Select
    Range(rngcustrelpo, rngcustrelpo.End(xlDown)).Select
    ActiveWorkbook.Worksheets("BACKORDER").Sort.SortFields.Add Key:=ActiveSheet.UsedRange, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("BACKORDER").Sort
        .SetRange ActiveSheet.UsedRange
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Set rngcustrelpo1 = rngcustrelpo.Offset(1, 0)
    Range(rngcustrelpo1, rngcustrelpo1.End(xlDown)).Select
    Selection.Copy
End Sub

However, it is not sorting the data like I am expecting. I am not sure what I am missing here.

AcsErno
2#
AcsErno Reply to 2018-02-14 15:38:32Z

Key:=ActiveSheet.UsedRange is a complete misunderstanding of the sort method. (Usedrange covers the whole used area on the sheet - often "empty" cells, too.) The same applies to .SetRange ActiveSheet.UsedRange. It is not bad just needless. SetRange is needed when you want to limit the area to be sorted. If you want to sort on only one key (column), then change this

ActiveWorkbook.Worksheets("BACKORDER").Sort.SortFields.Add Key:=ActiveSheet.UsedRange, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("BACKORDER").Sort
    .SetRange ActiveSheet.UsedRange
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

to this:

With ActiveWorkbook.Worksheets("BACKORDER").Sort
    .Key rngcustrelpo
    .Header = xlYes
    .MatchCase = False
    .Order:=xlAscending
    .Orientation = xlTopToBottom
    .SortOn:=xlSortOnValues
    .DataOption:= xlSortTextAsNumbers
    .SortMethod = xlPinYin
    .Apply
End With

And you can find more info here: Excel SortFields add then sort and here: Most efficient way to sort and sort syntax VBA

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.360725 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO