vbaexcel

Sort Worksheet that's not Active/Visible


So I use the code below to sort the Worksheet, and it works...but only if you're on the Worksheet it's trying to sort. If you're not it sends an Error:

Run-time error '1004': The Sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort box isn't the same or blank.

I'm going to need to keep this Worksheet hidden, so making it active isn't really an option. Am I missing a line in the code?

Thanks

CODE:

Sheet23.Columns("A:C").Sort key1:=Range("A2"), order1:=xlAscending, _ 
               key2:=Range("B2"), order2:=xlDescending, Header:=xlYes

Solution

  • You should always qualify Range() or Cells() with a worksheet, otherwise they refer to the ActiveSheet:

        Sheet23.Columns("A:C").Sort key1:=Sheet23.Range("A2"), order1:=xlAscending, _ 
                                    key2:=Sheet23.Range("B2"), order2:=xlDescending, _
                                    Header:=xlYes
    

    or without that repetition:

    With Sheet23
        .Columns("A:C").Sort key1:=.Range("A2"), order1:=xlAscending, _ 
                             key2:=.Range("B2"), order2:=xlDescending, _
                             Header:=xlYes
    End With