Is there a way to sort the sheet tabs within a workbook using a macro?
Is there a way to sort the sheet tabs within a workbook using a macro?
Private Sub Workbook_NewSheet(ByVal Sh As Object)
' 14 Apr 2017
Const FirstToSort As Integer = 1
Dim ShName As String
Dim i As Integer
Dim Done As Boolean
Application.ScreenUpdating = False
With ActiveSheet
Do
ShName = .name
ShName = InputBox("What is this worksheet's name?", "Give a name", ShName)
If Len(ShName) = 0 Then ShName = .name
On Error Resume Next
.name = ShName
Loop While Err
End With
With ThisWorkbook.Worksheets
Do
Done = True
For i = FirstToSort To .Count - 1
If .Item(i).name > .Item(i + 1).name Then
.Item(i + 1).Move Before:=.Item(i)
Done = False
End If
Next i
Loop Until Done
End With
Application.ScreenUpdating = True
End Sub
Observe the code line "Const FirstToSort As Integer = 1".
It determines that all sheets should be sorted. If your workbook has a summary sheet, for example, that should always be the first tab you can set the constant to 2 (or 3 or any number) to exclude those sheets from the sort.
We literally have that macro here on teachexcel.
That page provides the code and a desription of it.