Delete on Workbook Close

helpexcel

Well-known Member
Joined
Oct 21, 2009
Messages
656
I'm trying to clear the worksheet and delete any added worksheets when the workbook is closed. this is the code I put in ThisWorkbook, but it doesn't work.
Code:
Private Sub Workbook_Deactivate()

    Set ws9 = Sheet9
    ws9.Cells.Delete
    
Dim ws As Worksheet
Application.DisplayAlerts = False
For Each ws In Worksheets
If ws.Name <> "Main Sheet" Then ws.Delete
Next
    
    
    
End Sub
 

Excel Facts

Which came first: VisiCalc or Lotus 1-2-3?
Dan Bricklin and Bob Frankston debuted VisiCalc in 1979 as a Visible Calculator. Lotus 1-2-3 debuted in the early 1980's, from Mitch Kapor.
If you want it to work when you close the workbook, you will need to use the BeforeClose event, rather than the deactivate event. However you will also need to save the workbook, otherwise you will loose the changes.
 
Upvote 0
You're welcome & thanks for the feedback.
 
Upvote 0
I tried to add two sheets to the code, and now it deletes all of the sheets but the last one added.

VBA Code:
Dim WS As Worksheet
For Each WS In Worksheets
If WS.Name <> "Main Sheet" Or "Total" Or "Graph" Then WS.Delete
Next
 
Upvote 0
Are you trying to keep sheets Main, Total & Graph and delete all the others?
 
Upvote 0
Ok, how about
VBA Code:
Dim WS As Worksheet
For Each WS In Worksheets
   Select Case WS.Name
      Case "Main Sheet", "Total", "Graph"
      Case Else
         WS.Delete
   End Select
Next
 
Upvote 0
Solution

Forum statistics

Threads
1,215,219
Messages
6,123,680
Members
449,116
Latest member
HypnoFant

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