Deleting Sheets with VBA

mhockey88

New Member
Joined
Jul 9, 2015
Messages
5
Hi - I'm trying to figure out how to delete extraneous sheets in a workbook using VBA. The following code works, but only for keeping the one sheet titled "New Month" obviously. There are two other sheets I need to keep, "Column Guide" and "Data Validation". I tried to use this: If ws.Name <> "New Month" OR "Data Validation" OR "Column Guide" Then ws.delete, but it did not work

For Each ws in Sheets
Application.DisplayAlerts=False
If ws.Name <> "New Month" Then ws.delete
Next
Application.DisplayAlerts=True

Thanks!
 

Some videos you may like

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).

ranman256

Well-known Member
Joined
Jun 17, 2014
Messages
1,954
Code:
Sub Macro1()
Application.DisplayAlerts = False
For Each ws In Sheets
      'keep these
    If ws.Name = "New Month" Or ws.Name = "xxx" Then
    Else
       ws.Delete
    End If
Next
Application.DisplayAlerts = True
End Sub
 

AlphaFrog

MrExcel MVP
Joined
Sep 2, 2009
Messages
16,381
Try this...

Code:
If ws.Name <> "New Month" And ws.Name <> "Column Guide" And ws.Name <> "Data Validation" Then ws.Delete
 

Rick Rothstein

MrExcel MVP
Joined
Apr 18, 2011
Messages
36,690
Office Version
  1. 2010
Platform
  1. Windows
Give this a try...
Code:
Sub RemoveExtraneousSheets()
  Dim X As Long
  Application.DisplayAlerts = False
  For X = Sheets.Count To 1 Step -1
    If Sheets(X).Name <> "New Month" And Sheets(X).Name <> "Column Guide" _
       And Sheets(X).Name <> "Data Validation" Then Sheets(X).Delete
  Next
  Application.DisplayAlerts = True
End Sub
 

Watch MrExcel Video

Forum statistics

Threads
1,122,748
Messages
5,597,914
Members
414,190
Latest member
PuzzlerUK

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
Top