excel将工作表按笔画或拼音顺序排序

来源:转载

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为按笔画顺序排序。在代码中进行相应的更改即可按不同的方法和次序进行排序。

分享给朋友:
您可能感兴趣的文章:
随机阅读: