I have this code that actually do exactly what I want to:
goes to the specific range, copy the table in a new range and reorder the table.
Here is the code:
Sub copy_paste_sort()
Dim oneRange As Range
Dim aCell As Range
Dim WS_Count As Integer
Dim I As Integer
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
For I = 1 To WS_Count
Set oneRange = Range("CZ269:DA294")
Set aCell = Range("DA269")
Range("CW269:CX294").Select
Selection.Copy
Range("CZ269:DA294").Select
ActiveSheet.Paste
oneRange.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo
Next I
End Sub
The problem is: the code is not working in all worksheets, it is repeating n times in the first worksheet.
You never tell the code to go to the next worksheet. Also, your selections don't look necessary.
Sub copy_paste_sort()
Dim oneRange As Range
Dim aCell As Range
Dim WS_Count As Integer
Dim I As Integer
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
For I = 1 To WS_Count
Set oneRange = worksheets(I).Range("CZ269:DA294")
Set aCell = worksheets(I).Range("DA269")
worksheets(I).Range("CW269:CX294").Copy worksheets(I).Range("CZ269:DA294")
oneRange.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo
Next I
End Sub
Also - Since you are sorting the range, I am guessing that it containsvalues, rather than formulas. If that is the case, you can replace
worksheets(I).Range("CW269:CX294").Copy worksheets(I).Range("CZ269:DA294")
with
worksheets(I).Range("CZ269:DA294").Value = worksheets(I).Range("CW269:CX294").Value
The advantage of this is that it is slightly faster, and doesn't use your clipboard.
Try it as,
Sub copy_paste_sort()
Dim I As Long
' Begin the loop.
For I = 1 To ActiveWorkbook.Worksheets.Count
With Worksheets(I)
With .Range("CW269:CX294")
.Copy destination:=.Range("CZ269")
.Offset(0, 3).Cells.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo
End With
End With
Next I
End Sub
You were looping through I
as the index number of the workshjeets but not doing anything with it. The With Worksheets(I) ... End With
references eac h worksheet in turn. Note that Range(...)
becomes .Range(...)
so that it knows what worksheet is its parent.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.