简体   繁体   中英

Excel macro to work on all worksheets in workbook

Trying to get macro to work on all worksheets in workbook I want to Copy selection to separate location in same worksheet but paste values only.

Then sort selection at the new location based on first column.

This is what I have

Sub SortALLsheets()
Dim wsheet As Worksheet

For Each wsheet In ActiveWorkbook.Worksheets
Sheets(wsheet.Name).Select
    Range("AJ4:AK1732").Select
    Selection.Copy
    Range("AP4").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    Range("AP4:AQ1732").Select
    WS.Sort.SortFields.Add Key:=Range("AP4:AP1732"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With WS.Sort
        .SetRange Range("AP4:AQ1732")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

Next wsheet

End Sub

I get an error on the Ws.sort line

All assistance much appriciated thanks Ronald

Select is rarely needed in excel macros. Try this update.

Sub SortALLsheets()
Dim wsheet As Worksheet

For Each wsheet In ActiveWorkbook.Worksheets
    wsheet.Range("AP4:AQ1732").value=wsheet.Range("AJ4:AK1732").value
    wsheet.Sort.SortFields.Add Key:=wsheet.Range("AP4:AP1732"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With wsheet.Sort
        .SetRange wsheet.Range("AP4:AQ1732")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

Next wsheet

End Sub

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM