Looping or Repeating on all worksheets

S

sayerplayer

I want to repeat this on all worksheets, without individually selecting each
sheet and running the macro. I want the macro to run on all sheets and stop
at the end. I am using this on a weekly back order report, so the worksheet
names change weekly, but the name of each column is the same from A:L.
Please help, I can't seem to find info about this.
Here is what I have found so far, it works for each sheet individually, but
I want it to do all sheets at once.

Sub SortWorksheets()

Dim N As Integer
Dim M As Integer
Dim FirstWSToSort As Integer
Dim LastWSToSort As Integer
Dim SortDescending As Boolean
Dim sh As Worksheet

SortDescending = False

If ActiveWindow.SelectedSheets.Count = 1 Then
FirstWSToSort = 1
LastWSToSort = Worksheets.Count
Else
With ActiveWindow.SelectedSheets
For N = 2 To .Count
If .Item(N - 1).Index <> .Item(N).Index - 1 Then
MsgBox "You cannot sort non-adjacent sheets"
Exit Sub
End If
Next N
FirstWSToSort = .Item(1).Index
LastWSToSort = .Item(.Count).Index
End With
End If

For M = FirstWSToSort To LastWSToSort
For N = M To LastWSToSort
If SortDescending = True Then
If UCase(Worksheets(N).Name) > _
UCase(Worksheets(M).Name) Then
Worksheets(N).Move Before:=Worksheets(M)
End If
Else
If UCase(Worksheets(N).Name) < _
UCase(Worksheets(M).Name) Then
Worksheets(N).Move Before:=Worksheets(M)
End If
End If
Next N
Next M
For Each sh In ThisWorkbook.Worksheets

Columns("A:L").Select
Selection.Sort Key1:=Range("F2"), Order1:=xlAscending, Key2:=Range("B2") _
, Order2:=xlAscending, Key3:=Range("H2"), Order3:=xlAscending,
Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False,
Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal, DataOption2:=xlSortTextAsNumbers,
DataOption3 _
:=xlSortNormal
Next
End Sub
 
D

Dave Peterson

For Each sh In ThisWorkbook.Worksheets
with sh
.Columns("A:L").Sort _
Key1:=.Range("F2"), Order1:=xlAscending, _
Key2:=.Range("B2"), Order2:=xlAscending, _
Key3:=.Range("H2"), Order3:=xlAscending, _
Header:=xlGuess, OrderCustom:=1, _
MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal, DataOption2:=xlSortTextAsNumbers, _
DataOption3:=xlSortNormal
end with
Next sh

notice the dots in front of each range (.columns(), .range()). That means that
they belong to the object in the previous With statement--in this case sh.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top