EyyJP
EyyJP

Reputation: 45

How can I modify this code to reference cells in a different worksheet

Sub SortDataWithoutHeader()
Range("A1", Range("A1").End(xlDown)).Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlNo
End Sub

my interface buttons are in a sheet called 'tools' and the data being manipulated is in a sheet called 'data'

Upvotes: 0

Views: 34

Answers (1)

BigBen
BigBen

Reputation: 49998

Something like this. A With statement can be helpful here. Note the periods before every Range, Cells, and Rows call within the With block. The period is necessary to actually reference ws, which is the sheet you want.

Sub SortDataWithoutHeader()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Data")
    
    With ws
        Dim lastRow As Long
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        
        .Range("A1:A" & lastRow).Sort Key1:=.Range("A1"), Order1:=xlAscending, Header:=xlNo
    End With
End Sub

Upvotes: 1

Related Questions