Forum Discussion

seanrm100_'s avatar
seanrm100_
Copper Contributor
Sep 27, 2019
Solved

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

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

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

3 Replies

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

    • seanrm100_'s avatar
      seanrm100_
      Copper Contributor
      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!

Resources