SOLVED

Mystery error happens randomly, but more often when running from a formcontrol button...

Copper Contributor

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

3 Replies
best response confirmed by seanrm100_ (Copper Contributor)
Solution

@seanrm100_ 

You 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.

Wow, that's what I get for copying and pasting code, I can't believe I've been I've been dealing with this for weeks over something so silly. Thanks!

@seanrm100_ 

You're welcome! Glad it resolved your issue.

Don't worry, this is the most common and obvious mistake. :)

1 best response

Accepted Solutions
best response confirmed by seanrm100_ (Copper Contributor)
Solution

@seanrm100_ 

You 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.

View solution in original post