Table of Contents
Introduction/Problem Statement/Business Need:
This article is to Delete Worksheet in a workbook using Excel VBA code.
In many cases, the user wants to delete the worksheet without manual intervention.
This code will delete a worksheet by its name.
Sub KDataScience_DeleteWorksheetByName() 'Delete Sheet By giving Sheet Name in Double Quotes ThisWorkbook.Worksheets("Sheet1").Delete End Sub
This code will delete a worksheet by Index number.
Sub KDataScience_DeleteWorksheetByIndexNumber() 'Delete Sheet by giving Index Number ThisWorkbook.Worksheets(1).Delete End Sub
This code will delete the last worksheet in the workbook.
Sub KDataScience_DeleteLastWorksheet() 'Delete Last Sheet in workbook. ThisWorkbook.Worksheets(Sheets.Count).Delete End Sub
Delete Worksheet Without Deleting Prompt:
Deleting prompt has been shown in below screenshot :
This code will delete sheets without deleting prompt:
Sub KDataScience_DeleteSheetsWithoutDeletingPrompt() ' "Application.displayalerts" restrict the prompt msg. Application.DisplayAlerts = False Sheets("Sheet2").Delete Application.DisplayAlerts = True End Sub
This code will delete the “Data” sheet if it exists:
Sub KDataScience_DeleteSheetsIfExists() Dim Iloop% Application.DisplayAlerts = False For Iloop = Worksheets.Count To 0 Step -1 If ThisWorkbook.Worksheets(Iloop).Name = "Data" Then ThisWorkbook.Worksheets(Iloop).Delete End If Next Application.DisplayAlerts = True End Sub
If you want to delete worksheet in a workbook then you may use any of the above code instead of manually doing it. KDataScience would prefer you to use code to delete the sheet without “Deleting” Prompt.