Question posted 2013 · +8 upvotes
I am trying to sort a range within a separate sheet. However, I keep getting this message:
'1004': "The sort reference is not valid. Make sure it's within the data you want to sort, and the first Sort By box isn't the same or blank.
I have checked the ranges and they all exist and are working.
The code is below:
Dim EmpBRange As String
EmpBRange = Sheets("EmployeeData").Cells(Cells.Rows.Count, "B").End(xlUp).Row
Worksheets("EmployeeData").Range("K3:K" & EmpBRange).Sort Key1:=Range("K3:K" & EmpBRange), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Thanks in advance
Accepted answer +13 upvotes
I suspect you need to fully qualify the Key1 range, because you are calling the code from a different sheet:
Worksheets("EmployeeData").Range("K3:K" & EmpBRange).Sort Key1:=Worksheets("EmployeeData").Range("K3:K" & EmpBRange)
This is generally a good idea.
VBA Core objects referenced (3)
Cells.Rows— Refer to Rows and ColumnsRange— Refer to Cells by Using a Range ObjectRange— Delete Duplicate Entries in a Range
Top vba Q&A (6)
- Difference between Visual Basic 6.0 and VBA +122 (2009)
- VBA – how to conditionally skip a for loop iteration +116 (2011)
- VBA: Test if string begins with a string? +53 (2013)
- html parsing of cricinfo scorecards +47 (2012)
- Code to loop through all records in MS Access +46 (2011)
- Access VBA | How to replace parts of a string with another string +44 (2011)
vba solutions on this site
.