Search code examples
vbasortingexcelworksheet

vba sort worksheets: why capital / non-capital?


I have a code which sorts my worksheets from sheet 9 until the last sheet. I found that it works perfectly. The only thing I do not understand: the code somehow sorts capitals first and after that, all sheets with names that do not start with capitals follow. Why is that?

this is the sort code:

Sub SortSheets()
   Application.ScreenUpdating = False
   Dim I As Integer, J As Integer

For I = 9 To Sheets.Count
  For J = I + 1 To Sheets.Count
    If Sheets(J).Name < Sheets(I).Name Then
      Worksheets(J).Move before:=Worksheets(I)
    End If
  Next J
Next I

End Sub

It now sorts all the right worksheets but first, all the worksheets with a name that starts with a capital are sorted, and after that, all the sheets with names that start with a non-capital are sorted.


Solution

  • While the code provided by simoco fixes the sorting - the reason why the capital letters were sorted first is because they have lower ASCII values.

    Here's a table for reference. ASCII values

    You can get the ASCII value of a string in VBA using the Asc(myString) function.