我想在我的excel文件中對工作表排序。我發現this代碼是有效的。但問題是我的表名是1_abc,2_adf,3_dasf,11_ad等。此代碼將11_ad放在2_adf和3_dasf之前。我希望根據表格中的「_」(第一個下劃線)之前的數字對錶格進行排序。我怎麼能這樣做?excel vba按數字順序排序表
################################ UPDATE1我修改了代碼,如下所示。但在按降序排序:(我想按升序排序的這個
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
重新標記您的工作表01_abc,02_adf,03_dasf,11_ad等 – Jeeped
您在兩個塊中使用'>'比較 - 請再次看原始代碼 –
感謝Tim。它現在正在工作 – user2543622