Microsoft KB Archive/812386

From BetaArchive Wiki
Knowledge Base


How to sort worksheets alphanumerically in a workbook in Excel

Article ID: 812386

Article Last Modified on 3/21/2007



APPLIES TO

  • Microsoft Office Excel 2007
  • Microsoft Office Excel 2003
  • Microsoft Excel 2002 Standard Edition
  • Microsoft Excel 2000 Standard Edition
  • Microsoft Excel 97 Standard Edition



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 Microsoft Office Excel 2007 and in earlier versions of Microsoft Excel, you cannot sort macro sheets because they are displayed in the Visual Basic Editor.

MORE INFORMATION

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure. However, they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.

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 more 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 How to run the sample code for the Office XP programs from Knowledge Base articles


212536 How to run sample code from Knowledge Base articles in Office 2000


173707 How to run sample code from Knowledge Base articles



Additional query words: XL97 XL2000 XL2002 XLXP XL2003 XL2007 Excel97 Excel2000 Excel2002 ExcelXP Excel2003 Excel2007

Keywords: kbexpertisebeginner kbmacro kbprogramming kbautomation kbvba kbhowto KB812386