sort columns

  • Thread starter Thread starter pierreeng
  • Start date Start date
P

pierreeng

Hi dude, can someone tell me what's wrong with the line with *.


Sub Sort()

x = Worksheets.Count

For m = 3 To x
*Worksheets(m).Range("A6:O200").Select
Selection.sort Key1:=Range("O6"), Order1:=xlAscending,
Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
Next m
End Sub

I tried to run but it showed "Select method of range class failed".Can
someone specify where the errors are?

My idea is to sort the rows according to the data in column O, and i
wanna do this fr my 3rd sheet to the last sheet.

Thks n haf a nice day ahead.
 
Hi
change the line
Worksheets(m).Range("A6:O200").Select

to
Worksheets(m).Activate
Worksheets(m).Range("A6:O200").Select
 
Selections can only be done in the parent worksheet, so if Worksheets(m)
isn't active, the selection fails.

One way:

Application.Goto Worksheets(m).Range("A6")
Range("A6:O200").Select


However, it would be far better to eliminate the selections altogether.
Code that addresses ranges directly is smaller, faster, and IMO, easier
to maintain:

Public Sub Sort1()
Dim m As Long
For m = 3 To Worksheets.Count
With Worksheets(m)
.Range("A6:O200").Sort _
Key1:=.Range("O6"), _
Order1:=xlAscending, _
Header:=xlGuess, _
OrderCustom:=1, _
MatchCase:=False, _
Orientation:=xlTopToBottom
End With
Next m
End Sub


The With...End With is used so that the .Range("O6") in Key1 is
referenced to the same worksheet as the range to be sorted.
 
Back
Top