VBA to delete sheets (with name) when closing

sassriverrat

Well-known Member
Joined
Oct 4, 2018
Messages
655
I have a workbook that creates sheets named "Noon", "Noon2", "Noon3" etc based on the users' needs (button will generate a new "Noon" on demand. I'd like a piece of code that will delete all sheets named "Noon+# so that the original template is not saved over. How might I do this. I presume piece of code goes in close (boolean) piece of thisworkbook.

Thanks!
 

Excel Facts

What do {} around a formula in the formula bar mean?
{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.
Code:
With Workbooks("NAME") 'EDIT

For i = 1 to .Sheets(.Sheets.Count)

If Instr(.Sheets(i).Name, "Noon")<>0 And Len(.Sheets(i).Name)>4 Then 
    Application.DisplayAlerts = False    
    Sheets(i).Delete
    Application.DisplayAlerts = True
Next i

End With

Try this. Make sure you make a backup before executing the code.
 
Last edited:
Upvote 0
This would be more robust to the brief:

Code:
Application.DisplayAlerts = False

For Each sh In ThisWorkbook.Worksheets
    If LCase(sh.Name) Like "noon*" Then
        If Len(sh.Name) > 4 Then
            If IsNumeric(Mid(sh.Name, 5, Len(sh.Name))) Then sh.Delete
        Else
            sh.Delete
        End If
    End If
Next

Application.DisplayAlerts = True
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,179
Members
453,021
Latest member
Justyna P

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