Sort Worksheets

P

Patrick C. Simonds

Is there any way (using VBA code) to place all WorkSheets in a WorkBook in
alphabetical order?
 
G

Gary Keramidas

you can give this a try, i think it was chip pearson's code:

Sub SortWorksheets()
'Chip Pearson

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

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

End Sub
 
E

eliano

Hi Patrick.

see Chip Pearson at:


http://www.cpearson.com/excel/sortws.htm


my friend Norman Jones proposed a little variation to the good Chip
code:

instead of:
-----------------------------------------------------------------
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
-----------------------------------------------------------------

try:

If (UCase(Worksheets(N).Name) > UCase(Worksheets(M).Name)) = _
SortDescending Then
Worksheets(N).Move Before:=Worksheets(M)
End If

Regards
Eliano
 
G

Gord Dibben

Quick and dirty sort by name.

Sub sort_sheets()
'Mike H June 13th, 2007
Dim I As Integer, J As Integer

For I = 1 To Sheets.Count - 1
For J = I + 1 To Sheets.Count
If UCase(Sheets(I).Name) > UCase(Sheets(J).Name) Then
Sheets(J).Move Before:=Sheets(I)
End If
Next J
Next I
End Sub

For more methods and flexibility see Chip pearson's site.

http://www.cpearson.com/excel/sortws.aspx


Gord Dibben MS Excel MVP
 
A

Anant Basant

You can use the following macro:

Sub SheetSortMacro()

' Macro to work with chartsheets also

Dim shtCount As Long
Dim i As Long, j As Long

On Error GoTo MacroError

shtCount = ActiveWorkbook.Sheets.Count

For i = 1 To shtCount - 1
For j = i + 1 To shtCount
If UCase(Sheets(j).Name) < UCase(Sheets(i).Name) Then
Sheets(j).Move Before:=Sheets(i)
End If
Next j
Next i

ExitHere:
Exit Sub

MacroError:
MsgBox Err.Description
Resume ExitHere
End Sub
 

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