Excel中沒有內置工作表排序的命令或方法,我們可以用VBA來實現工作表排序。下面的VBA代碼可以將工作表按其名稱的拼音或筆畫的順序來排序,同時還可以指定升序或降序。
Sub SortWorksheets()
Dim SortOrd, SortM, ActiveSht As String
Dim NumSht()
ActiveSht = ActiveWorkbook.ActiveSheet.Name
On Error Resume Next
n = Sheets.Count
If n = 1 Then
MsgBox "只有一張工作表,無需排序!"
End
End If
ReDim NumSht(1 To n)
For i = 1 To n
NumSht(i) = Sheets(i).Name
Next
‘在此設置工作表排序方法和排序方向
‘SortM = xlPinYin為按拼音順序, SortM = xlStroke為按筆畫順序
‘SortOrd = xlAscending為升序,SortOrd = xlDescending為降序
SortOrd = xlAscending
SortM = xlPinYin
Set sht = Sheets.Add
sht.Move after:=Sheets(n + 1)
sht.Visible = False
With sht.Range("A1:A" & n)
.NumberFormat = "@"
.Value = Application.WorksheetFunction.Transpose(NumSht())
.Sort Key1:=sht.Range("A1"), Order1:=SortOrd, SortMethod:=SortM
NumSht() = Application.WorksheetFunction.Transpose(.Value)
End With
For i = 1 To n
Sheets(NumSht(i)).Move Before:=Sheets(i)
Next
Application.DisplayAlerts = False
sht.Delete
Application.DisplayAlerts = True
ActiveWorkbook.Worksheets(ActiveSht).Select
End Sub
代碼中的SortOrd變量指定工作表的排序次序,xlAscending為升序,xlDescending為降序。SortM變量指定工作表的排序方法,xlPinYin指定工作表按拼音順序排序,xlStroke為按筆畫順序排序。在代碼中進行相應的更改即可按不同的方法和次序進行排序。