Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting in Excel

Status
Not open for further replies.

sjh

Programmer
Oct 29, 2001
263
US
Hi,
I used the following code in a module to sort the fields in a sheet named 'mySheet'. But I get run-time error 1004: method 'range' of object '_worksheet' failed. What's wrong with my code??

mySheet.Range(Cells(8, 1), Cells(84, 30)).Sort Key1:=mySheet.Range("A10"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal

Thank you!
 
...in a sheet named 'mySheet'....

You need to learn and understand the difference between the worksheet Object and the worksheet Name.

The sort method must be applied to the worksheet Object.

Try this and see if you can see the difference:
[blue]
Code:
Sub Sort1()
  With Worksheets("mySheet")
    .Range(Cells(8, 1), Cells(84, 30)).Sort _
       Key1:=.Range("A10"), _
       Order1:=xlAscending, _
       Header:=xlGuess, _
       OrderCustom:=1, _
       MatchCase:=False, _
       Orientation:=xlTopToBottom, _
       DataOption1:=xlSortNormal
  End With
End Sub
[/color]

Or, if you prefer, you can do it this way:
[blue]
Code:
Sub Sort2()
Dim mySheet As Worksheet
  Set mySheet = Worksheets("mySheet")
[/color]
Code:
  mySheet.Range(Cells(8, 1), Cells(84, 30)).Sort Key1:=mySheet.Range("A10"), Order1:=xlAscending, Header:= _
    xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    DataOption1:=xlSortNormal
[blue]
Code:
  Set mySheet = Nothing
End Sub
[/color]

The second method uses your code as posted. The only difference is it defines mySheet as a Worksheet Object so that the sort can be executed.

Incidently, if you put the line
[blue]
Code:
  Option Explicit
[/color]

as the first line in your code modules, you can (usually) get a little more assistance from the compiler. In this case it should have reported that "mySheet" was an undefined variable. That may have led you into finding the solution offered by my second example (where I defined mySheet as a Worksheet).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top