I'm trying to pass a range to a subroutine, but its throwing up a "Method 'Range' of object '_Global' failed" error.
In the main I declare and define the range variable I want to use:
Sub maintest()
Dim ScheduledSort As Range
Set ScheduledSort = Range("F4:F321")
Call test(ScheduledSort)
End Sub
Then in the subroutine test I want it to sort using the range I passed it from the routine above:
Sub test(RangeForSort)
Sheets("SheetTest").Select
' Sort in descending order
ActiveWorkbook.Worksheets("SheetTest").AutoFilter.Sort.SortFields.Add _
Key:=Range("RangeForSort"), SortOn:=xlSortOnValues, Order:=xlDescending, _
DataOption:=xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("SheetTest").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
I think its going wrong at the Key:=Range("RangeForSort") but I can't work out why and how to fix it.
What is it I'm doing wrong with the Range and how do I fix it such that I can pass it any Range to sort on?
And if you have a better suggestion for what I'm trying to do, feel free to add! :-)
Key:=RangeForSortor ...Key:=Range(RangeForSort.address)...RangeForSortis a range object, not a string. You might also have incorrect worksheet as indicated by Jeeped, but the second version should take care of that.maintest()sub. You could directly pass the range to yourtest()sub.maintest()is a snippet from a larger piece that calls other routines... In the sub rountine thattestsub is cut from, I sort on some criteria passed to it from the sub above and then I filter on specific cells. I need to filter on different criteria and then sort on different columns. Having a generalised subroutine that did the filter and sort seemed the best way to do that.