@dee's answer has resolved your issue, but as I see you are checking too many names, and I would like to provide a more elegant solution to your problem.
The idea is very simple: dump the "If" and the "else if" cases in two separate arrays, and check if the sheet name is in each array, and take the corresponding action. Since there is no action in the ElseIf
clause, we can rewrite the logic with If/ElseIf
only. I utilize Jimmy Pena's function IsInArray
in this answer to make the check.
Also, I have made a few changes in the code, to make it a little more readable:
Sub CleanSheets()
Dim x As Long ' Long is safer and faster
Dim aFirstCategory(4) As String
Dim aSecondCategory(1) As String
' Note that checking for the sheet name is usually not very robust.
' You might be interested in the Like function to make your checks more flexible
aFirstCategory(0) = "MIR - Raw"
aFirstCategory(1) = "MRR - Raw"
aFirstCategory(2) = "MWR - Raw"
aFirstCategory(3) = "PL - Raw"
aFirstCategory(4) = "SHP - Raw"
aSecondCategory(0) = "Dahshboard"
x = 1 ' I would check with ForEach wSheet in Sheets instead
Do 'Until should go to the end of the loop, else the last sheet will not be checked
If IsInArray(Sheets(x).Name, aFirstCategory) Then
'clear them
Sheets(x).Cells.ClearContents ' Sheets(x).ClearContents gives error I think
ElseIf not IsInArray(Sheets(x).Name, aSecondCategory) Then
'delete the sheet
Application.DisplayAlerts = False
Sheets(x).Delete
Application.DisplayAlerts = True
x = x - 1
End If
x = x + 1
Loop Until x = Sheets.Count
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function