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!
 

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
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
 
Upvote 0
Try this...

Code:
If ws.Name <> "New Month" And ws.Name <> "Column Guide" And ws.Name <> "Data Validation" Then ws.Delete
 
Upvote 0
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
 
Upvote 0

Forum statistics

Threads
1,213,501
Messages
6,114,010
Members
448,543
Latest member
MartinLarkin

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