title: excel vba sort sheet numerically
body: <p>I want to sort sheets in my excel file. I found <a href="http://www.vbaexpress.com/kb/getarticle.php?kb_id=72" rel="nofollow noreferrer">this</a> code which works. But the problem is that my sheet names are 1_abc, 2_adf, 3_dasf, 11_ad etc. This code puts 11_ad before 2_adf and 3_dasf. I would like to sort sheets based upon number before "_" (first underscore) in my sheet name. How could I do the same?</p>
  
  ################################UPDATE1
  
  <p>I modified the code as below. But it is sorting in descending order :(. I want to sort in ascending order</p>
  
  <pre><code>Option Explicit
  
  Sub SortWorksheets()
  
      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
  
           'Change the 1 to the worksheet you want sorted first
          FirstWSToSort = 1
          LastWSToSort = Worksheets.Count
      Else
          With ActiveWindow.SelectedSheets
              For N = 2 To .Count
                  If .Item(N - 1).Index &lt;&gt; .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 CLng(Split(Worksheets(N).Name, "_")(0)) &gt; _
     CLng(Split(Worksheets(M).Name, "_")(0)) Then
                      Worksheets(N).Move Before:=Worksheets(M)
                  End If
              Else
                  If CLng(Split(Worksheets(N).Name, "_")(0)) &gt; _
     CLng(Split(Worksheets(M).Name, "_")(0)) Then
                      Worksheets(N).Move Before:=Worksheets(M)
                  End If
              End If
          Next N
      Next M
  
  End Sub
  </code></pre>