How can I exclude sheets for VBA alphabetizing code?

48 Views Asked by At

I'm using the code below to alphabetize my worksheets in my workbook for excel. However, I have four sheets that I don't want alphabetized. It is the first two sheets and the last two sheets: "Table of contents", "Project Template", "Help", and "Settings.

Sub SortWorksheetsAlphabetially()

'Turn off screen updating
Application.ScreenUpdating = False

'Create variables
Dim wb As Workbook
Dim wsCount As Integer
Dim i As Integer
Dim j As Integer

'Declare the workbook
Set wb = Workbooks(ActiveWorkbook.Name)

'Count the number of worksheets
wsCount = wb.Worksheets.Count

'Loop through all worksheets and move
For i = 1 To wsCount - 1
    For j = i + 1 To wsCount
        If wb.Worksheets(j).Name < wb.Worksheets(i).Name Then
            wb.Worksheets(j).Move before:=wb.Worksheets(i)
        End If
    Next j
Next i

'Turn on screen updating
Application.ScreenUpdating = True

End Sub

I tried using

If ws.Name <> "Table of Contents" And ws.Name <> "Project Template" And ws.Name <> "Help" And ws.Name <> "Settings" Then

in different places in the code

2

There are 2 best solutions below

0
BigBen On

By adjusting the bounds of your loops to exclude the last two and first two worksheets:

' Exclude last two sheets
wsCount = wb.Worksheets.Count - 2

' Start at the third sheet
For i = 3 To wsCount - 1

Full code:

Sub SortWorksheetsAlphabetially()

    Application.ScreenUpdating = False
    
    Dim wb As Workbook
    Dim wsCount As Long, i As Long, j As Long
    
    Set wb = ActiveWorkbook
    
    wsCount = wb.Worksheets.Count - 2
    
    For i = 3 To wsCount - 1
        For j = i + 1 To wsCount
            If wb.Worksheets(j).Name < wb.Worksheets(i).Name Then
                wb.Worksheets(j).Move before:=wb.Worksheets(i)
            End If
        Next j
    Next i
    
    Application.ScreenUpdating = True

End Sub
0
Aldert On

if it is the first 2 sheets and the last 2 sheets, you can use:

For i = 3 To wsCount - 3
    For j = i + 1 To wsCount - 2
        If wb.Worksheets(j).Name < wb.Worksheets(i).Name Then
            wb.Worksheets(j).Move before:=wb.Worksheets(i)
        End If
    Next j
Next i

I shortened the for by skipping the first 2 ad the last two but also in the inner loop do the wsCount - 2