Deleting Worksheets Based on Worksheet Name

aryaden

Board Regular
Joined
Jun 9, 2021
Messages
101
Office Version
  1. 2019
Platform
  1. Windows
I currently have this code to delete all worksheets in a workbook other than the one named "Data" before running other macros. Currently if "Data" is the only worksheet in the workbook I get an error and the code stops running. This macro is a part of a larger set of macros and I have many workbooks to apply these series of macros on. Is there any way to tweak this code so that even if "Data" is the only sheet I will not get an error?

VBA Code:
Sub Delete() 
Dim xWs As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False

For Each xWs In Application.ActiveWorkbook.Worksheets
If xWs.Name <> "Data" Then
xWs.Delete
End If
Next

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

Thanks for all the help in advance!
 

Excel Facts

Square and cube roots
The =SQRT(25) is a square root. For a cube root, use =125^(1/3). For a fourth root, use =625^(1/4).
You should not get an error if it's the only sheet.
What error do you get & which line is highlighted when you click debug?
 
Upvote 0
The code should work just fine with a single sheet named "Data". But if the sheet is named "data", it will fail. SO update that line to:
Code:
If LCase(xWs.Name) <> "data" Then
 
Upvote 0
You should not get an error if it's the only sheet.
What error do you get & which line is highlighted when you click debug?
xWs.Delete is highlighted in yellow when "Data" is the only sheet
 
Upvote 0
You didn't answer the first part of my question. But do you have any hidden sheets?
 
Upvote 0
Solution
Glad we could help & thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,215,216
Messages
6,123,669
Members
449,114
Latest member
aides

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top