How to delete worksheet when closing the workbook

Mr.MJ 1 Reputation point
2022-04-12T10:09:28.407+00:00

Hi

How to automatically delete a specific sheet (the sheet name containing with (.delete) ) in a workbook via VBA when closing it.

Many thanks

J.

Microsoft 365 and Office | Development | Other
Microsoft 365 and Office | Excel | For business | Windows
Developer technologies | Visual Basic for Applications
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Emily Hua-MSFT 27,796 Reputation points
    2022-04-13T09:45:55.933+00:00

    Hi @Mr.MJ

    Welcome to Q&A forum ~
    Please note, "office-excel-itpro" tag focues more on general issue, for issues related to VBA code, it's best wait to the VBA experts' suggestions.

    According to the same thread "Delete a sheet on closing the workbook", I suggest you try following code. (Please Note: Since the web site is not hosted by Microsoft, the link may changed without notice. Microsoft does not guarantee the accuracy of this information.)

    Private Sub Workbook_BeforeClose(Cancel As Boolean)  
    Dim sht As Worksheet  
    Application.DisplayAlerts = False  
    
    
        For Each sht In Sheets  
            If sht.Name Like "*.delete" Then  
                sht.Delete  
            End If  
        Next sht  
    
    ThisWorkbook.Save  
    Application.DisplayAlerts = True  
    End Sub  
    

    Hope the information could be helpful.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.