Sort that will work on any worksheet on the active workbook

117 views Asked by At

this code seem to work only when the active worksheet is labelled as "analysis 1"

I have commented the working part and write my own code in order to try and make the code to run on any active worksheet on this work book this is the line that has an error but also see the screen shot

ActiveWorkbook.Worksheets("Analysis 1")

enter image description here

i tried to use activeWorksheet method i also tried using dim ws as worksheet ActiveWorkbook.activeWorksheet(ws.name).sort.. i tried using a for loop as well please see below code

Sub sortColumns()
'
' sortColumns Macro
'
  For Each s In ActiveWorkbook.Sheets
'
    'ActiveWorkbook.Worksheets("Analysis 1").Sort.SortFields.Clear
     ' Dim ws As Worksheet
    'ActiveWorkbook.Worksheets("Analysis 1").Sort.SortFields.Add2 Key:=Range( _
        "G5:G781951"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
        
        ActiveWorkbook.s.Sort.SortFields.Clear
        ActiveWorkbook.s.Sort.SortFields.Add2 Key:=Range( _
        "G5:G781951"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.s.Sort
        .SetRange Range("A4:H781951")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
    Next s
   
End Sub
1

There are 1 answers

0
VBasic2008 On

Sort All Worksheets

Option Explicit

Sub SortAllWorksheets()
  
    Const HEADER_ROW As Long = 4
    Const SORT_COLUMN As Long = 7
  
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim ws As Worksheet, rg As Range, RowOffset As Long
    
    For Each ws In wb.Worksheets
        With ws
            With .UsedRange
                RowOffset = HEADER_ROW - .Row
                Set rg = .Resize(.Rows.Count - RowOffset).Offset(RowOffset)
            End With
            With .Sort
                .SortFields.Clear
                .SortFields.Add2 _
                    Key:=rg.Columns(SORT_COLUMN), _
                    SortOn:=xlSortOnValues, _
                    Order:=xlAscending, _
                    DataOption:=xlSortNormal
                .SetRange rg
                .Header = xlYes
                .MatchCase = False
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
                .Apply
            End With
        End With
    Next ws
        
    MsgBox "Worksheets sorted.", vbInformation
      
End Sub