excel vba sort sheet numerically

2019-07-28 06:34发布

I want to sort sheets in my excel file. I found this 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?

################################UPDATE1

I modified the code as below. But it is sorting in descending order :(. I want to sort in ascending order

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 <> .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)) > _
   CLng(Split(Worksheets(M).Name, "_")(0)) Then
                    Worksheets(N).Move Before:=Worksheets(M)
                End If
            Else
                If CLng(Split(Worksheets(N).Name, "_")(0)) > _
   CLng(Split(Worksheets(M).Name, "_")(0)) Then
                    Worksheets(N).Move Before:=Worksheets(M)
                End If
            End If
        Next N
    Next M

End Sub

1条回答
一纸荒年 Trace。
2楼-- · 2019-07-28 07:29

Instead of this:

If UCase(Worksheets(N).Name) > UCase(Worksheets(M).Name) Then     

you need something like this:

If CLng(Split(Worksheets(N).Name,"_")(0)) > _
   CLng(Split(Worksheets(M).Name,"_")(0)) Then
查看更多
登录 后发表回答