I am trying to sort a range within a separate sheet. However, I keep getting this message:
\'1004\': \"The sort reference is not valid. Make sure it\'s wit
I have been trying to use the Sort
method but from Powershell. And I only got The sort reference is not valid
part without the Make sure it's within the data you want to sort, and the first Sort By box isn't the same or blank
part. This is how I got here.
My issue was due to having disregarded an argument to the Sort
call. If you look closer to the documentation you will see there is a Type
parameter tucked away in the middle of the key and order params:
expression .Sort(Key1, Order1, Key2, Type, Order2, Key3, Order3, Header, OrderCustom, MatchCase, Orientation, SortMethod, DataOption1, DataOption2, DataOption3)
I have passed $null
for that one and my method call started working. The next strange thing was that for some reason Key2 / Order2
was disregarded. I am using all 3 keys to sort my data. The fix to that was to swap Key2 / Order2
with Key3 / Order3
arguments within the method call. Strangely, it has worked.
I suspect you need to fully qualify the Key1
range, because you are calling the code from a different sheet:
Worksheets("EmployeeData").Range("K3:K" & EmpBRange).Sort Key1:=Worksheets("EmployeeData").Range("K3:K" & EmpBRange)
This is generally a good idea.