
Excel將工作表按筆畫或拼音順序排序
Excel中沒有內置工作表排序的命令或方法,我們可以用VBA來實現工作表排序。下面的VBA代碼可以將工作表按其名稱的拼音或筆畫的順序來排序,同時還可以指定升序或降序。
Sub SortWorksheets()Dim SortOrd, SortM, ActiveSht As StringDim NumSht()ActiveSht = ActiveWorkbook.ActiveSheet.NameOn Error Resume Nextn = Sheets.CountIf n = 1 ThenMsgBox "只有一張工作表,無需排序!"EndEnd IfReDim NumSht(1 To n)For i = 1 To nNumSht(i) = Sheets(i).NameNext
‘在此設置工作表排序方法和排序方向‘SortM = xlPinYin為按拼音順序, SortM = xlStroke為按筆畫順序‘SortOrd = xlAscending為升序,SortOrd = xlDescending為降序SortOrd = xlAscendingSortM = xlPinYin
Set sht = Sheets.Addsht.Move after:=Sheets(n + 1)sht.Visible = FalseWith sht.Range("A1:A" & n).NumberFormat = "@".Value = Application.WorksheetFunction.Transpose(NumSht()).Sort Key1:=sht.Range("A1"), Order1:=SortOrd, SortMethod:=SortMNumSht() = Application.WorksheetFunction.Transpose(.Value)End WithFor i = 1 To nSheets(NumSht(i)).Move Before:=Sheets(i)NextApplication.Displayalerts = Falsesht.DeleteApplication.Displayalerts = TrueActiveWorkbook.Worksheets(ActiveSht).SelectEnd Sub
代碼中的SortOrd變量指定工作表的排序次序,xlAscending為升序,xlDescending為降序。SortM變量指定工作表的排序方法,xlPinYin指定工作表按拼音順序排序,xlStroke為按筆畫順序排序。在代碼中進行相應的更改即可按不同的方法和次序進行排序。

