XL: How to Sort Sheets in a Workbook (812386)



The information in this article applies to:

  • Microsoft Excel 2002
  • Microsoft Excel 2000
  • Microsoft Excel 97 for Windows

SUMMARY

Although there is no built-in tool to alphanumerically sort sheets, charts, Microsoft Excel 4.0 macro sheets, and dialog sheets in a workbook, you can do this with a macro.

Note In Excel 97, Excel 2000 and Excel 2002, you cannot sort modules because they are displayed in the Visual Basic Editor.

MORE INFORMATION

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs. If you have limited programming experience, you may want to contact a Microsoft Certified Partner or the Microsoft fee-based consulting line at (800) 936-5200. For more information about Microsoft Certified Partners, see the following Microsoft Web site: For additional information about the support options available from Microsoft, visit the following Microsoft Web site:
Sub Sort_Active_Book()
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult
'
' Prompt the user as which direction they wish to
' sort the worksheets.
'
   iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
     & "Clicking No will sort in Descending Order", _
     vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
   For i = 1 To Sheets.Count
      For j = 1 To Sheets.Count - 1
'
' If the answer is Yes, then sort in ascending order.
'
         If iAnswer = vbYes Then
            If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
               Sheets(j).Move After:=Sheets(j + 1)
            End If
'
' If the answer is No, then sort in descending order.
'
         ElseIf iAnswer = vbNo Then
            If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
               Sheets(j).Move After:=Sheets(j + 1)
            End If
         End If
      Next j
   Next i
End Sub
For additional information about how to run this macro code in Excel, click the following article numbers to view the articles in the Microsoft Knowledge Base:

290140 OFFXP: How to Run Sample Code from Knowledge Base ArticlesOFFXP: How to Run Sample Code from Knowledge Base Articles

212536 OFF2000: How to Run Sample Code from Knowledge Base Articles

173707 OFF97: How to Run Sample Code from Knowledge Base Articles


Modification Type:MajorLast Reviewed:5/28/2003
Keywords:kbhowto KB812386