我正在尝试对工作簿中的所有工作表进行排序,但以下代码一直给我一个错误。任何和所有的帮助将非常感激。
Dim i As Worksheet
For Each i In ThisWorkbook.Sheets
Worksheets(i).Columns("A").Select
Selection.Sort key1:=Range("A1"), order1:=xlAscending, Header:=xlYes
Next
End Sub
答案 0 :(得分:1)
为了提高效率,请不要使用select(不需要排序)。以下代码应该有效:
Sub aaa()
Dim i As Worksheet
Dim r As Range
For Each i In ThisWorkbook.Sheets
Set r = i.Range("A:A")
r.Sort key1:=i.Range("A1"), order1:=xlAscending, Header:=xlYes
Next
End Sub
答案 1 :(得分:0)
稍微多一点,但是如果你想按字母顺序排序,我在互联网上看到的,做这样的事情:
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
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 UCase(Worksheets(N).Name) > UCase(Worksheets(M).Name) Then
Worksheets(N).Move before:=Worksheets(M)
End If
Else
If UCase(Worksheets(N).Name) < UCase(Worksheets(M).Name) Then
Worksheets(N).Move before:=Worksheets(M)
End If
End If
Next N
Next M
End Sub
如果要对降序进行排序,请将SortDescending
更改为true。
您可以通过更改FirstWSToSort
和LastWSToSort
轻松更改开始/结束工作簿。