Help Understanding my Sort VBA code

keef2

Board Regular
Joined
Jun 30, 2022
Messages
185
Office Version
  1. 365
Platform
  1. Windows
Hi all,

The issue was I had a multilevel sort code that I wanted to sort by Job # then By Box # both in ascending order. However, for some reason I noticed in multiple areas that it was not properly sorted mostly because the data has a bunch of different style job #'s. Here is what was happening originally: (take a look at box 221 where the 1701 Cicero project was in the middle of 3XXX projects for no reason.
1661796416149.png


Here was my original code:

VBA Code:
Sub MultiLevelSort()

Worksheets("User Inputs").Sort.SortFields.Clear

Range("A2:G" & Range("A" & Rows.Count).End(xlUp).Row).Sort Key1:=Range("D2"), Key2:=Range("B2"), Header:=xlYes, _
    Order1:=xlAscending, Order2:=xlAscending, DataOption1:=xlSortTextAsNumbers
 
End Sub


My new code which applies the correct sorting is the following. Can anyone help explain why I needed to add the 2nd range sort to get this to work properly? Or is there a better way to code this? Thanks in advance!
VBA Code:
Sub MultiLevelSort()

Worksheets("User Inputs").Sort.SortFields.Clear

Range("A2:G" & Range("A" & Rows.Count).End(xlUp).Row).Sort Key1:=Range("D2"), Key2:=Range("B2"), Header:=xlYes, _
    Order1:=xlAscending, Order2:=xlAscending, DataOption1:=xlSortTextAsNumbers
   
Range("A2:G" & Range("A" & Rows.Count).End(xlUp).Row).Sort Key1:=Range("B2"), Header:=xlYes, _
    Order1:=xlAscending
   
End Sub
 

Excel Facts

Difference between two dates
Secret function! Use =DATEDIF(A2,B2,"Y")&" years"&=DATEDIF(A2,B2,"YM")&" months"&=DATEDIF(A2,B2,"MD")&" days"

Forum statistics

Threads
1,214,625
Messages
6,120,598
Members
448,973
Latest member
ksonnia

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top