Sep 27 2019 03:55 PM
So I have a macro that creates sheets, transfers data to them, and then cleans it. All is well and good, but I often get the
'Runtime Error 1004: The sort reference isn't valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank'
error when I'm trying to sort the data. At the start of the macro, it checks whether specific sheets exist in the data workbook (not the one running the macro) and deletes them if they do, before creating new ones. I've noticed about 50% of the time I get this error when trying to sort the data in the sheets:
ws.Range("A1:Z200").Sort Key1:=Columns("A"), Order1:=xlAscending, Header:=xlNo
But when I delete the sheets manually before running the macro again, it always works. The weirdest part is that I added a formcontrol button to run the macro, but when I use it, I get the error message every single time. I've also tried clearing the sheet's contents instead of deleting it but I get the same results. Anyone seen inconsistent mystery errors before and know what I can do to fix it? Thanks
Sep 27 2019 06:46 PM
SolutionYou should qualify the key with the Sheet reference like this...
ws.Range("A1:Z200").Sort Key1:=ws.Columns("A"), Order1:=xlAscending, Header:=xlNo
Or more precisely this...
ws.Range("A1:Z200").Sort Key1:=ws.Range("A1"), Order1:=xlAscending, Header:=xlNo
This should resolve the issue.
Sep 30 2019 06:16 AM
Sep 30 2019 06:33 AM
You're welcome! Glad it resolved your issue.
Don't worry, this is the most common and obvious mistake. :)
Sep 27 2019 06:46 PM
SolutionYou should qualify the key with the Sheet reference like this...
ws.Range("A1:Z200").Sort Key1:=ws.Columns("A"), Order1:=xlAscending, Header:=xlNo
Or more precisely this...
ws.Range("A1:Z200").Sort Key1:=ws.Range("A1"), Order1:=xlAscending, Header:=xlNo
This should resolve the issue.