Delete all worksheets vba excel

I am trying to delete all worksheets except the first 20 sheets

I have this code — Which I thought was working, but I just run it now and it only deletes some of the sheets.

Sub DeleteAll()
    i = Worksheets.Count
    For x = 21 To i
        Application.DisplayAlerts = False
        Worksheets(x).Delete
        Application.DisplayAlerts = True
    Next x
End Sub

shA.t's user avatar

shA.t

16.4k5 gold badges53 silver badges111 bronze badges

asked Sep 18, 2013 at 0:01

user2761190's user avatar

Do While Worksheets.Count > 20
   Worksheets(21).Delete
Loop

answered Sep 18, 2013 at 0:13

Tim Williams's user avatar

Tim WilliamsTim Williams

150k8 gold badges96 silver badges124 bronze badges

1

The sheet indexes change as you delete them. So when you have deleted sheet 21 suddenly you have another sheet 21 which is skipped and sheet 22 is deleted, etc.

One solution is to delete sheets in reverse order beginning with the last sheet. For example:

Sub DeleteAll()
    i = Worksheets.Count
    For x = i to 21 Step -1 '# <- please note the change here
        Application.DisplayAlerts = False
        Worksheets(x).Delete
        Application.DisplayAlerts = True
    Next x
End Sub

answered Sep 18, 2013 at 0:11

mechanical_meat's user avatar

mechanical_meatmechanical_meat

162k24 gold badges225 silver badges222 bronze badges

0

How to delete multiple Excel worksheets using Excel, VBA and Shortcut methods

METHOD 1. Delete multiple Excel worksheets using the sheet option

EXCEL

Select multiple worksheets > Right-click on one of the selected worksheets > Delete

1. Press and hold the Shift key and select the worksheets that you want to delete.
Note: in this example we are deleting three worksheets and therefore have selected three sheets.
Select multiple sheets - Excel
2. Right-click on any of the selected worksheets.
3. Click Delete.
Right-click on one of the selected worksheets and select Delete - Excel

METHOD 2. Delete multiple Excel worksheets using the ribbon option

EXCEL

Select multiple worksheets > Home tab > Cells group >  Delete > Delete Sheet

1. Press and hold the Shift key and select the worksheets that you want to delete.
Note: in this example we are deleting three worksheets and therefore have selected three sheets.
Select multiple sheets - Excel
2. Select the Home tab. Select Home tab - Excel
3. Click Delete in the Cells group.
4. Click Delete Sheet.
Click Delete and click Delete Sheet - Excel

METHOD 1. Delete multiple Excel worksheets using VBA

VBA

Sub Delete_Multiple_Excel_Worksheets()

‘declare variables
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet

Set ws1 = Worksheets(«Sheet1»)
Set ws2 = Worksheets(«Sheet2»)
Set ws3 = Worksheets(«Sheet3»)

‘delete three worksheets at the same time
ws1.Delete
ws2.Delete
ws3.Delete

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.

PREREQUISITES
Minimum Number of Worksheets: Have at least four worksheets in a workbook.
Worksheet Names: Have three worksheets named Sheet1, Sheet2 and Sheet3.

ADJUSTABLE PARAMETERS
Worksheets to Delete: Select worksheets that you want to delete by changing the Sheet1, Sheet2 and Sheet3 worksheet names in the VBA code to any worksheet in the workbook.

METHOD 2. Delete multiple Excel worksheets from a list of names that you want to delete using VBA

VBA

Sub Delete_Multiple_Excel_Worksheets()

Set ws1 = Worksheets(«Parameters»).Range(«D2»)
Set ws2 = Worksheets(«Parameters»).Range(«D3»)
Set ws3 = Worksheets(«Parameters»).Range(«D4»)

‘delete three worksheets at the same time
Worksheets(ws1.Value).Delete
Worksheets(ws2.Value).Delete
Worksheets(ws3.Value).Delete

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Minimum Number of Worksheets: Have at least four worksheets in a workbook, including the Parameters worksheet.
Worksheet Names: Have four worksheets named Parameters, Sheet1, Sheet2 and Sheet3.
Worksheets to Delete: Cells («D2»), («D3») and («D4») in the Parameters worksheet need to be populated with the names of the worksheets that you want to delete.

ADJUSTABLE PARAMETERS
Worksheets to Delete: Select worksheets that you want to delete by changing the worksheet names in cells («D2»), («D3») and («D4») in the Parameters worksheet.

METHOD 3. Delete multiple Excel worksheets from a list of names that you want to delete with a For Loop using VBA

VBA

Sub Delete_Multiple_Excel_Worksheets()

On Error Resume Next
For Each deletews In ThisWorkbook.Worksheets(«Parameters»).Range(«D2:D4»)
ThisWorkbook.Worksheets(deletews.Value).Delete

Next

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Minimum Number of Worksheets: Have at least four worksheets in a workbook, including the Parameters worksheet.
Worksheet Names: Have four worksheets named Parameters, Sheet1, Sheet2 and Sheet3.
Worksheets to Delete: Cell («D2»), («D3») and («D4») in the Parameters worksheet need to be populated with the names of the worksheets that you want to delete.

ADJUSTABLE PARAMETERS
Worksheets to Delete: Select worksheets that you want to delete by changing the worksheet names in cells («D2»), («D3») and («D4») in the Parameters worksheet.

METHOD 4. Delete multiple Excel worksheets from a list of names that you want to delete with a For Loop using VBA

VBA

Sub Delete_Multiple_Excel_Worksheets()

‘declare a variable
Dim ws As Worksheet

Set ws = Worksheets(«Parameters»)

For x = 2 To 4

On Error Resume Next

deletews = ws.Cells(x, 4).Value
Worksheets(deletews).Delete

Next

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.

PREREQUISITES
Minimum Number of Worksheets: Have at least four worksheets in a workbook, including the Parameters worksheet.
Worksheet Names: Have four worksheets named Parameters, Sheet1, Sheet2 and Sheet3.
Worksheets to Delete: Cell («D2»), («D3») and («D4») in the Parameters worksheet need to be populated with the names of the worksheets that you want to delete.

ADJUSTABLE PARAMETERS
Worksheets to Delete: Select worksheets that you want to delete by changing the names in cells («D2»), («D3») and («D4») in the Parameters worksheet.

Delete multiple worksheets using a Shortcut

SHORTCUT

WINDOWS SHORTCUT

NOTES
Select the worksheets that you want to delete, then action the shortcut. The shortcut will delete all of the selected worksheets.

Explanation about how to delete multiple worksheets

EXPLANATION

EXPLANATION
This tutorial explains and provides step by step instructions on how to delete multiple worksheets using Excel, VBA and Shortcut methods.

Excel Methods: Using Excel you can delete multiple worksheet with a ribbon or sheet option.

VBA Methods: Using VBA you can delete multiple worksheets by directly entering the names of the worksheets that you want to delete or by referencing to cells that capture the names of the worksheets that you want to delete.

Shortcut Method: Using a Shortcut you can delete multiple selected worksheets.

Содержание

  1. VBA Delete Sheet
  2. Excel VBA Delete Sheet
  3. How to Delete Excel Sheets using VBA Code?
  4. Example #1 – Delete Worksheet by using its Name
  5. Example #2 – Delete Worksheet by its Name with Variables
  6. Example #3 – Delete Active Worksheet
  7. Example #4 – Delete More than One Worksheet
  8. Recommended Articles
  9. How to Delete Sheets in Excel (Shortcuts + VBA)
  10. Delete Sheets Using Right-Click Options
  11. Keyboard Shortcuts to Delete the WorkSheets
  12. Hybrid Keyboard Shortcut to Delete Sheet
  13. Regular Keyboard Shortcut to Delete Sheet
  14. Legacy Keyboard Shortcut to Delete Worksheets
  15. Deleting the ActiveSheet Using VBA
  16. Deleting the Sheet Without Showing the Confirmation Prompt
  17. Deleting Sheet By Name (If It Exists) Using VBA
  18. Deleting All Sheets Except the Active Sheet Using VBA
  19. Delete All Sheets with a Specific Text String in the Name

VBA Delete Sheet

Excel VBA Delete Sheet

We use a “Delete Worksheet” method to delete a sheet in VBA. To apply this method, first, we need to identify which sheet we are deleting by calling the sheet name. We have two methods to do the same. First, we directly write sheet1.delete; the second method is sheets(sheet1).delete.

Table of contents

So, the syntax follows.

OR

So, first, we need to specify the sheet name by using either Worksheet or Sheets Object, then later, we can use the “Delete” method.

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Delete Sheet (wallstreetmojo.com)

How to Delete Excel Sheets using VBA Code?

Example #1 – Delete Worksheet by using its Name

Assume you have many sheets. We need to mention the worksheet’s name to delete a particular worksheet. For example, we have 3 different sheets named “Sales 2016”, “Sales 2017”, and “Sales 2018”.

If we want to delete the sheet named “Sales 2017,” then we have to mention the sheet name like the below.

Code:

The problem with mentioning the worksheet name is that we do not get to see the IntelliSense list of VBA. So, anyways, mention the method as “Delete.”

Code:

So this will delete the sheet named “Sales 2017“.

Error While Deleting the Worksheet: If we try to delete the worksheet that does not exist or mention the worksheet name wrongly, we will get the VBA error as “Subscript Out of Range.”

In the above, we got the “Subscript Out of Range” error because, in our workbook, there is no sheet name called “Sales 2017.”

Example #2 – Delete Worksheet by its Name with Variables

As we have seen in the above example, the moment we refer to the worksheet name by using the Worksheet object, we do not get to see the IntelliSense list. To get to see the IntelliSense list, we need to use variables.

Step 1: First, declare the variable as Worksheet.

Code:

Step 2: Since the worksheet is an object variable, we need to set the variable to the specific worksheet using the “SET” word.

Code:

The variable “Ws” refers to the “Sales 2017” worksheet.

Step 3: Now, using the variable “Ws,” we can access all the IntelliSense lists of the worksheet.

Code:

Step 4: From the IntelliSense list, select the “Delete” method.

Code:

Like this, using variables, we can access the IntelliSense list.

Example #3 – Delete Active Worksheet

ActiveSheet is nothing but whichever worksheet is active or selected at the moment. For this method, we need not mention the worksheet name. For example, look at the VBA code VBA Code VBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task. read more .

ActiveSheet.Delete

Right now, the active sheet is “Sales 2017”.

If we run the code, it will delete the active sheet, “Sales 2017.”

Now, we will select “Sales 2016.”

Now, it will delete the active sheet, “Sales 2016.”

Like this, we can use the “Active Sheet” object to delete the worksheet.

Note: To use this method, we must be sure what we are doing with the ActiveSheet and which sheet will be active.

Example #4 – Delete More than One Worksheet

In our above examples, we have seen how to delete a single sheet, but what if we have multiple worksheets? For example, let us say we want to delete 10 worksheets.

We cannot keep writing 10 lines of code to delete the worksheet, so we need to use loops to loop through the collection of worksheets and delete them.

The below code will loop through the worksheets and delete all the worksheets in the workbook.

Code:

The above code will throw an error because it attempts to delete all the sheets in the workbook. So, to avoid this, we need to retain at least one worksheet.

If we want to delete all the worksheets except the active sheet, then we need to use the below code.

Code:

Similarly, we can use the code below if we do not want to delete a specific worksheet but all other worksheets.

Code:

The above code will delete all the worksheets except the worksheet named “Sales 2018.”

Recommended Articles

This article has been a guide to VBA Delete Sheet. Here, we learn how to delete worksheets using VBA coding, practical examples, and a downloadable Excel template. You may also have a look at other articles related to Excel VBA: –

Источник

How to Delete Sheets in Excel (Shortcuts + VBA)

When working with Excel, you spend most of your time on the worksheet (which is the area that has all the cells and everything that happens there).

Working efficiently with Excel also means that you have to work with multiple worksheets within the same workbook.

Excel allows you easily add multiple worksheets in the workbook, at the same time you can also easily delete these worksheets.

In this Excel tutorial, I will show you how to quickly delete worksheets in Excel. I would cover multiple methods such as using keyboard shortcuts, options in the ribbon, and VBA to delete sheets in Excel.

This Tutorial Covers:

Delete Sheets Using Right-Click Options

The easiest way to delete a worksheet in Excel is by using this simple two-click mouse technique.

Suppose, you have a worksheet that has three sheets as shown below, and you want to delete Sheet1.

Below are the steps to do this:

  1. Right-click on the sheet that you want to delete
  2. Click on the delete option
  3. In the prompt that shows up, click on the Delete button

You can also use the above technique on sheets that are not even the active sheet. For example, if I’m currently on Sheet1 and I want to delete Shee3, then I can simply right-click on Sheet3 and delete it.

You can also use the same technique to delete multiple sheets at once.

For example, if I want to delete Sheet2 and Sheet3 in one go, I can hold the control key and click on Sheet2 and Sheet3 one by one (while still holding the control key).

By holding the control key, Excel would allow me to select multiple sheets at one go. Once I’m done selecting the desired sheets, I can leave the control key. now I can right-click on any of the selected sheets tabs, and click on delete.

Keyboard Shortcuts to Delete the WorkSheets

There is not one but two-and-half keyboard shortcuts that you can use to delete worksheets in Excel.

I say two and a half because one of the shortcuts he uses the mouse as well as the keyboard (and is still a faster way to do it)

Hybrid Keyboard Shortcut to Delete Sheet

To delete the selected worksheet or worksheets, right-click and then press the D key on your keyboard.

Personally, I find this a lot faster than just using the mouse to delete a worksheet (as I covered in the above section)

Regular Keyboard Shortcut to Delete Sheet

If you would rather prefer to ditch the mouse and only use the keyboard, the above keyboard shortcut will delete the active sheet or the selected sheets.

You need to press these keys in succession (i.e., one after the other)

While it may look like a slightly longer keyboard shortcut, once you get used to it it’s just as fast as any other technique covered in this tutorial

Legacy Keyboard Shortcut to Delete Worksheets

Like everyone else, Excel also has a past, and it’s not that pretty. I’m talking about the pre-ribbon style era.

For compatibility reasons, Excel still allows some of those old keyboard shortcuts to work in the newer versions. and in many cases, those earlier shortcuts are shorter and better.

Luckily, there is a legacy keyboard shortcut that works to delete worksheets in Excel

Deleting the ActiveSheet Using VBA

When it comes to deleting one sheet, or a couple of worksheets, it’s better to use the above-mentioned methods.

While VBA can automate the process, it’s usefulness comes in when you have to repeat the task multiple times.

As you will see, with VBA you can do a lot more when it comes to deleting worksheets in Excel.

So I’ll take you to more advanced use cases, but before that let’s see how to simply delete the active worksheet using VBA.

Below is the VBA code that will delete the active sheet:

If you’re using it in the immediate window, you can simply use the below line:

When you use the above code to delete the active sheet, Excel would show you a prompt where you would have to click the delete button to confirm the action.

Deleting the Sheet Without Showing the Confirmation Prompt

The confirmation prompt message box is a useful feature that makes sure that you have a chance to cancel the deletion of the sheet in case you have run the code accidentally/erroneously

But if you already know what you’re doing, getting this prompt can be quite irritating.

so here is the VBA code that would make sure that the sheets are deleted but you do not see any confirmation prompt message box.

In the above code, I have set the Application.DisplayAlerts property to false, which means that Excel will not show you any display alerts while the code is running.

It’s also really important to make sure that you turn it back to true at the end of the code to restore the functionality (as you can see I have done in the above code).

Caution: When you set the Application.DisplayAlerts property to false, Excel would simply delete the worksheet and there would be no way to recover it. so I advise you make a backup copy before you use this kind of code.

Deleting Sheet By Name (If It Exists) Using VBA

VBA allows you to automate the process of deleting a specific worksheet (on multiple worksheets) based on the sheet name.

For example, if you have a worksheet with the name ‘Sales’, you can use the below code to delete it:

This code would only delete the sheet that has the name Sales.

It’s useful when you have a workbook with a lot of sheets and you don’t want to sift through all the worksheets find the one with the name sales and delete it manually.

With the above code, it does not matter how many worksheets there are in the workbook it would simply delete the sales worksheet.

And since I have not changed the Application.DisplayAlert property, you will see a prompt where you would have to click the delete button to confirm the duration of the sales sheet.

In case you want to delete multiple sheets based on their name, you can do that as well.

For example, the below code would delete the sheets with the name Sales, Marketing, Finance:

Deleting All Sheets Except the Active Sheet Using VBA

If you have a workbook with multiple worksheets in it, and you want to delete all the worksheets except the active sheet, VBA is probably one of the better methods to do this.

Below is the VBA code that would delete all the sheets except the active sheet in the workbook.

Note that I have said the Application.DisplayAlerts property to falls at the beginning of the code, as I don’t want to see a prompt for every sheet that is deleted.

Delete All Sheets with a Specific Text String in the Name

This is a slightly more advanced use case of using VBA effectively when deleting worksheets.

Suppose you have a workbook with many different worksheets and you want to delete all the worksheets that have a specific text string in them then you can easily do that using VBA.

For example, below I have a workbook where I want to delete all the worksheets that have the text string “Sales” in them.

Below is the VBA code that would do that:

The above code uses the if-then statement to go through all the worksheets in the workbook. It checks the name of all these worksheets and if the name contains the word “Sales”, then that worksheet is deleted.

If you want to change the code and look for any other text string, you can change that in the fifth line of the above code.

Also note that I’ve used an asterisk (*), which is a wild card character, on both sides of the text string that we are looking for in the worksheet name. This ensures that no matter where the string appears in the name of the worksheet, it would still be deleted.

You can also modify the code to make sure that only those worksheets are deleted where the text string appears at the beginning of the worksheet name.

For example, if you want to delete those sheets where the term sales appear at the beginning, use the following code in the fifth line.

Here, I’ve used the wild card character only after the text drink and not before it. This will make sure at while checking the names of the worksheet, only those would satisfy the criteria where the term ‘Sales’ is at the beginning of the name.

So these are some of the methods that you can use when you want to delete sheets in Excel. In most cases, you can easily do this right within the worksheet by using the mouse or the keyboard shortcut.

But in case you have a heavy workbook with a lot of worksheets and you want to quickly delete specific kinds of sheets then you can also use VBA.

I hope you found this tutorial useful.

Other Excel tutorials you may also like:

Источник

Excel VBA Delete Sheet: Step-by-Step Guide and 6 Examples to Delete Sheets with Macros - FeaturedIn this VBA Tutorial, you learn how to delete sheets in Excel (in different ways) with macros.

This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.

Use the following Table of Contents to navigate to the section you’re interested in.

Related VBA and Macro Tutorials

The following VBA and macro tutorials may help you better understand and implement the contents below:

  • General VBA constructs and structures:
    • Learn about commonly-used VBA terms here.
    • Learn how to work with the Visual Basic Editor (VBE) here.
    • Learn how to create and work with VBA Sub procedures here.
    • Learn how to work with object methods here.
    • Learn how to declare and work with variables here.
    • Learn how to work with data types here.
    • Learn how to work with arrays here.
  • Practical VBA applications and macro examples:
    • Learn other operations you can carry out when working with Excel worksheets here.

You can find additional VBA and Macro Tutorials in the Archives.

#1: Delete Sheet by Position

VBA Code to Delete Sheet by Position

To delete a sheet by its position using VBA, use a statement with the following structure:

Sheets(SheetIndex).Delete

Process Followed by VBA Code to Delete Sheet by Position

Identify sheet to delete by position > delete sheet

VBA Statement Explanation

  1. Item: Sheets.
    • VBA Construct: Workbook.Sheets property.
    • Description: The Workbook.Sheets property returns a Sheets collection representing all the sheets within the workbook you deal with. Identify a single object from this Sheets collection by specifying the appropriate index number (SheetIndex).

      When deleting a worksheet, you can work with the Workbook.Worksheets property. Workbook.Worksheets represents a Sheets collection representing all worksheets within the workbook you deal with.

      When deleting a chart sheet, you can work with the Workbook.Charts property. Workbook.Charts returns a Sheets collection representing all chart sheets within the workbook you deal with.

  2. Item: SheetIndex.
    • VBA Construct: Index parameter/number of the sheet you want to delete.
    • Description: The Index parameter/number of a sheet allows you to identify a single object (worksheet or chart sheet) from the Sheets collection you work with.

      The Index parameter/number represents the position of the sheet, worksheet or chart sheet in the tab bar of the workbook you deal with, from left to right. For example, 1 is the first (leftmost) sheet/worksheet/chart sheet.

      When specifying the Index parameter/number, consider the following:

      • The count usually includes hidden sheets/worksheets/chart sheets as well.
      • If you’re working with the Workbook.Worksheets property, the count includes worksheets but not chart sheets.
      • If you’re working with the Workbook.Charts property, the count includes chart sheets but not worksheets.

      If you explicitly declare a variable to represent SheetIndex, use the Long data type.

  3. Item: Delete.
    • VBA Construct: Worksheet.Delete method or Chart.Delete method.
    • Description: The Delete method deletes the object (worksheet or chart sheet) you identify with Sheets(SheetIndex).

      When you delete a sheet with the Delete method, Excel usually displays (by default) a dialog box asking the user to confirm the deletion. Please refer to the appropriate section below to delete a sheet with no prompt.

Macro Example to Delete Sheet by Position

The following macro deletes the first sheet (Sheets(mySheetIndex)) in the workbook where the macro is stored (ThisWorkbook). The macro suppresses the prompt that asks the user to confirm the sheet deletion (Application.DisplayAlerts = False).

Sub deleteSheet()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-delete-sheet/

    'declare variable to hold index number of sheet you want to delete
    Dim mySheetIndex As Long

    'specify index number of sheet you want to delete
    mySheetIndex = 1

    'suppress the dialog box that asks the user to confirm the sheet deletion
    Application.DisplayAlerts = False

    'identify sheet you want to delete, and delete it
    ThisWorkbook.Sheets(mySheetIndex).Delete

    're-enable the display of alerts and messages
    Application.DisplayAlerts = True

End Sub

Effects of Executing Macro Example to Delete Sheet by Position

The following GIF illustrates the results of executing the macro example. The first sheet in the workbook (Sheet1) is deleted.

Macro deletes sheet by position

#2: Delete Active Sheet

VBA Code to Delete Active Sheet

To delete the active sheet with VBA, use a statement with the following structure:

ActiveSheet.Delete

Process Followed by VBA Code to Delete Active Sheet

Identify active sheet > delete sheet

VBA Statement Explanation

  1. Item: ActiveSheet.
    • VBA Construct: Application.ActiveSheet property.
    • Description: The Application.ActiveSheet property returns an object representing the active sheet.
  2. Item: Delete.
    • VBA Construct: Worksheet.Delete method or Chart.Delete method.
    • Description: The Delete method deletes the object (worksheet or chart sheet) returned by ActiveSheet (the active sheet).

      When you delete a sheet with the Delete method, Excel usually displays (by default) a dialog box asking the user to confirm the deletion. Please refer to the appropriate section below to delete a sheet with no prompt.

Macro Example to Delete Active Sheet

The following macro deletes the active sheet (ActiveSheet). The macro suppresses the prompt that asks the user to confirm the sheet deletion (Application.DisplayAlerts = False).

Sub deleteActiveSheet()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-delete-sheet/

    'suppress the dialog box that asks the user to confirm the sheet deletion
    Application.DisplayAlerts = False

    'identify active sheet, and delete it
    ActiveSheet.Delete

    're-enable the display of alerts and messages
    Application.DisplayAlerts = True

End Sub

Effects of Executing Macro Example to Delete Active Sheet

The following GIF illustrates the results of executing the macro example. The active sheet (Sheet2) is deleted.

Macro deletes active sheet

#3: Delete Sheet by Name

VBA Code to Delete Sheet by Name

To delete a sheet by name using VBA, use a statement with the following structure:

Sheets(SheetName).Delete

Process Followed by VBA Code to Delete Sheet by Name

Identify sheet to delete by name > delete sheet

VBA Statement Explanation

  1. Item: Sheets.
    • VBA Construct: Workbook.Sheets property.
    • Description: The Workbook.Sheets property returns a Sheets collection representing all the sheets within the workbook you deal with. Identify a single object from this Sheets collection by specifying the appropriate name (SheetName).

      When deleting a worksheet, you can work with the Workbook.Worksheets property. Workbook.Worksheets represents a Sheets collection representing all worksheets within the workbook you deal with.

      When deleting a chart sheet, you can work with the Workbook.Charts property. Workbook.Charts returns a Sheets collection representing all chart sheets within the workbook you deal with.

  2. Item: SheetName.
    • VBA Construct: Name of the sheet you want to delete.
    • Description: The name of a sheet allows you to identify a single object (worksheet or chart sheet) from the Sheets collection you work with.

      For these purposes, the sheet name is that displayed in the tab of the worksheet or chart sheet. If you explicitly declare a variable to represent SheetName, use the String data type.

  3. Item: Delete.
    • VBA Construct: Worksheet.Delete method or Chart.Delete method.
    • Description: The Delete method deletes the object (worksheet or chart sheet) you identify with Sheets(SheetName).

      When you delete a sheet with the Delete method, Excel usually displays (by default) a dialog box asking the user to confirm the deletion. Please refer to the appropriate section below to delete a sheet with no prompt.

Macro Example to Delete Sheet by Name

The following macro deletes the sheet named “delete Sheet” (Sheets(mySheetName)) in the workbook where the macro is stored (ThisWorkbook). The macro suppresses the prompt that asks the user to confirm the sheet deletion (Application.DisplayAlerts = False).

Sub deleteSheetByName()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-delete-sheet/

    'declare variable to hold name of sheet you want to delete
    Dim mySheetName As String

    'specify name of sheet you want to delete
    mySheetName = "delete sheet"

    'suppress the dialog box that asks the user to confirm the sheet deletion
    Application.DisplayAlerts = False

    'identify sheet you want to delete, and delete it
    ThisWorkbook.Sheets(mySheetName).Delete

    're-enable the display of alerts and messages
    Application.DisplayAlerts = True

End Sub

Effects of Executing Macro Example to Delete Sheet by Name

The following GIF illustrates the results of executing the macro example. The sheet named “delete sheet” is deleted.

Macro deletes sheet by name

#4: Delete Sheet Without Prompt or Warning

VBA Code to Delete Sheet Without Prompt or Warning

To delete a sheet without Excel displaying the usual prompt (warning) with VBA, use a macro with the following statement structure:

Application.DisplayAlerts = False
Sheets(SheetName).Delete
Application.DisplayAlerts = True

Process Followed by VBA Code to Delete Sheet Without Prompt or Warning

Suppress prompts > identify sheet to delete > delete sheet > enable prompts

VBA Statement Explanation

Lines #1 and #3: Application.DisplayAlerts = False | Application.DisplayAlerts = True

  1. Item: Application.DisplayAlerts.
    • VBA Construct: Application.DisplayAlerts property.
    • Description: The Application.DisplayAlerts property allows you to specify whether Excel displays alerts and messages while the macro is running. When you delete a sheet, the main alert that Excel usually displays (and you want to handle) is the dialog box that prompts the user to confirm the sheet deletion.

      Microsoft Excel will permanently delete this sheet. Do you want to continue?

      The default value of the Application.DisplayAlerts property is True. In such cases, Excel displays the dialog box prompting the user to confirm the sheet deletion.

  2. Item: False.
    • VBA Construct: New property value of Application.DisplayAlerts property.
    • Description: When you delete a sheet, you can suppress the dialog box that prompts the user to confirm the sheet deletion, by setting the Application.DisplayAlerts property to False.

      When you set Application.DisplayAlerts to False and Excel requires a response, Excel chooses the default response. When you delete a sheet, the default response to the dialog box prompting the user to confirm the sheet deletion is “Delete”. This results in Excel deleting the sheet.

  3. Item: True.
    • VBA Construct: New property value of Application.DisplayAlerts property.
    • Description: The default value of the Application.DisplayAlerts property is True. This results in Excel displaying alerts and messages while a macro is running.

      Generally, when you set Application.DisplayAlerts to False, Excel sets the property back to True upon finishing macro execution. Since there are exceptions (such as executing cross-process code), you can explicitly set Application.DisplayAlerts back to True after deleting the sheet.

Line #2: Sheets(SheetName).Delete

  1. Item: Sheets.
    • VBA Construct: Workbook.Sheets property.
    • Description: The Workbook.Sheets property returns a Sheets collection representing all the sheets within the workbook you deal with. Identify a single object from this Sheets collection by specifying the appropriate name (SheetName).

      When deleting a worksheet, you can work with the Workbook.Worksheets property. Workbook.Worksheets represents a Sheets collection representing all worksheets within the workbook you deal with.

      When deleting a chart sheet, you can work with the Workbook.Charts property. Workbook.Charts returns a Sheets collection representing all chart sheets within the workbook you deal with.

  2. Item: SheetName.
    • VBA Construct: Name of the sheet you want to delete.
    • Description: The name of a sheet allows you to identify a single object (worksheet or chart sheet) from the Sheets collection you work with.

      For these purposes, the sheet name is that displayed in the tab of the worksheet or chart sheet. If you explicitly declare a variable to represent SheetName, use the String data type.

  3. Item: Delete.
    • VBA Construct: Worksheet.Delete method or Chart.Delete method.
    • Description: The Delete method deletes the object (worksheet or chart sheet) you identify with Sheets(SheetName).

Macro Example to Delete Sheet Without Prompt or Warning

The following macro deletes the sheet named “delete sheet no prompt” (Sheets(mySheetName)) in the workbook where the macro is stored (ThisWorkbook) without displaying the prompt that asks the user to confirm the sheet deletion (Application.DisplayAlerts = False).

Sub deleteSheetNoPrompt()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-delete-sheet/

    'declare variable to hold name of sheet you want to delete
    Dim mySheetName As String

    'specify name of sheet you want to delete
    mySheetName = "delete sheet no prompt"

    'suppress the dialog box that asks the user to confirm the sheet deletion
    Application.DisplayAlerts = False

    'identify sheet you want to delete, and delete it
    ThisWorkbook.Sheets(mySheetName).Delete

    're-enable the display of alerts and messages
    Application.DisplayAlerts = True

End Sub

Effects of Executing Macro Example to Delete Sheet Without Prompt or Warning

The following GIF illustrates the results of executing the macro example. The sheet named “delete sheet no prompt” is deleted without a prompt or warning.

Macro deletes sheet with no prompt

#5: Delete Sheet if it Exists

VBA Code to Delete Sheet if it Exists

To delete a sheet if it exists with VBA, use a macro with the following statement structure:

On Error Resume Next
Sheets(SheetName).Delete
On Error GoTo 0

Process Followed by VBA Code to Delete Sheet if it Exists

Enable error handling > identify sheet to delete > delete sheet if it exists > disable error handling

VBA Statement Explanation

Line #1: On Error Resume Next

  1. Item: On Error Resume Next.
    • VBA Construct: On Error Resume Next statement.
    • Description: The On Error Resume Next statement specifies that, if an error occurs, control goes to the statement immediately following the statement where the error occurs. Execution continues at that statement that follows that where the error occurs.

      “Sheets(SheetName).Delete” usually returns run-time error 9 (subscript out of range) when the sheet identified by Sheets(SheetName) doesn’t exist. Without the On Error Resume Next statement, such error results in Excel displaying an error message and stopping macro execution.

      Therefore:

      • If the sheet named SheetName exists, Excel deletes the sheet as specified by “Sheets(SheetName).Delete”.
      • If the sheet named SheetName doesn’t exist, execution of the macro continues on the statement following “Sheet(SheetName).Delete”. Due to the On Error Resume Next statement, Excel handles the run-time error.

Line #2: Sheets(SheetName).Delete

  1. Item: Sheets.
    • VBA Construct: Workbook.Sheets property.
    • Description: The Workbook.Sheets property returns a Sheets collection representing all the sheets within the workbook you deal with. Identify a single object from this Sheets collection by specifying the appropriate name (SheetName).

      When deleting a worksheet, you can work with the Workbook.Worksheets property. Workbook.Worksheets represents a Sheets collection representing all worksheets within the workbook you deal with.

      When deleting a chart sheet, you can work with the Workbook.Charts property. Workbook.Charts returns a Sheets collection representing all chart sheets within the workbook you deal with.

  2. Item: SheetName.
    • VBA Construct: Name of the sheet you want to delete.
    • Description: The name of a sheet allows you to identify a single object (worksheet or chart sheet) from the Sheets collection you work with.

      For these purposes, the sheet name is that displayed in the tab of the worksheet or chart sheet. If you explicitly declare a variable to represent SheetName, use the String data type.

  3. Item: Delete.
    • VBA Construct: Worksheet.Delete method or Chart.Delete method.
    • Description: The Delete method deletes the object (worksheet or chart sheet) you identify with Sheets(SheetName).

      When you delete a sheet with the Delete method, Excel usually displays (by default) a dialog box asking the user to confirm the deletion. Please refer to the appropriate section above to delete a sheet with no prompt.

Line #3: On Error GoTo 0

  1. Item: On Error GoTo 0.
    • VBA Construct: On Error GoTo 0 statement.
    • Description: The On Error GoTo 0 statement disables the error handling specified by the On Error Resume Next statement. If you omit the On Error GoTo 0 statement, Excel generally disables the error handler automatically when exiting the procedure.

Macro Example to Delete Sheet if it Exists

The following macro deletes the sheet named “delete sheet if exists” (Sheets(mySheetName)) in the workbook where the macro is stored (ThisWorkbook), if such sheet exists. If the sheet doesn’t exist, the macro handles the error. The macro suppresses the prompt that asks the user to confirm the sheet deletion (Application.DisplayAlerts = False).

Sub deleteSheetIfExists()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-delete-sheet/

    'declare variable to hold name of sheet you want to delete
    Dim mySheetName As String

    'specify name of sheet you want to delete
    mySheetName = "delete sheet if exists"

    'suppress the dialog box that asks the user to confirm the sheet deletion
    Application.DisplayAlerts = False

    'enable error handling to deal with error that occurs when (if) you try to delete a sheet that doesn't exist
    On Error Resume Next

    'identify sheet you want to delete, and delete it
    ThisWorkbook.Sheets(mySheetName).Delete

    'disable error handling
    On Error GoTo 0

    're-enable the display of alerts and messages
    Application.DisplayAlerts = True

End Sub

Effects of Executing Macro Example to Delete Sheet if it Exists

The following GIF illustrates the results of executing the macro example. The sheet named “delete sheet if exists” is deleted.

Macro deletes sheet if it exists

#6: Delete Multiple Sheets

VBA Code to Delete Multiple Sheets

To delete multiple sheets with VBA, use a statement with the following structure:

Sheets(Array(SheetsList)).Delete

Process Followed by VBA Code to Delete Multiple Sheets

Identify multiple sheets to delete as an array > delete sheets

VBA Statement Explanation

  1. Item: Sheets.
    • VBA Construct: Workbook.Sheets property.
    • Description: The Workbook.Sheets property returns a Sheets collection representing all the sheets within the workbook you deal with. Identify a single object from this Sheets collection by specifying the appropriate name (SheetName).

      When deleting worksheets, you can work with the Workbook.Worksheets property. Workbook.Worksheets represents a Sheets collection representing all worksheets within the workbook you deal with.

      When deleting chart sheets, you can work with the Workbook.Charts property. Workbook.Charts returns a Sheets collection representing all chart sheets within the workbook you deal with.

  2. Item: Array(…).
    • VBA Construct: Array function.
    • Description: The Array function returns a Variant containing an array.
  3. Item: SheetsList.
    • VBA Construct: Argument list of Array function.
    • Description: A comma-delimited list of the values you assign to each of the array elements.

      You can generally identify specific objects from the Sheets collection you work with using an index number or the sheet name, as follows:

      • The index number represents the position of a sheet, worksheet or chart sheet in the tab bar of the workbook you deal with, from left to right. For example, 1 is the first (leftmost) sheet/worksheet/chart sheet.

        When specifying the Index parameter/number, consider the following:

        • The count usually includes hidden sheets/worksheets/chart sheets as well.
        • If you’re working with the Workbook.Worksheets property, the count includes worksheets but not chart sheets.
        • If you’re working with the Workbook.Charts property, the count includes chart sheets but not worksheets.
      • The sheet name is that displayed in the tab of the worksheet or chart sheet.
  4. Item: Delete.
    • VBA Construct: Worksheet.Delete method or Chart.Delete method.
    • Description: The Delete method deletes the object (worksheets or chart sheets) you identify with Sheets(Array(SheetsList)).

      When you delete a sheet with the Delete method, Excel usually displays (by default) a dialog box asking the user to confirm the deletion. Please refer to the appropriate section above to delete a sheet with no prompt.

Macro Example to Delete Multiple Sheets

The following macro deletes (i) the first 2 sheets, and (ii) the sheets named “delete multiple sheets 1” and “delete multiple sheets 2” (Sheets(mySheetNames)), in the workbook where the macro is stored (ThisWorkbook). The macro suppresses the prompt that asks the user to confirm the sheet deletion (Application.DisplayAlerts = False).

Sub deleteMultipleSheets()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-delete-sheet/

    'declare variable to hold Variant containing array whose elements are the index numbers or names of the sheets you want to delete
    Dim mySheetNames() As Variant

    'specify (using index numbers or names) the sheets you want to delete
    mySheetNames = Array(1, 2, "delete multiple sheets 1", "delete multiple sheets 2")

    'suppress the dialog box that asks the user to confirm the sheet deletion
    Application.DisplayAlerts = False

    'identify sheets you want to delete, and delete them
    ThisWorkbook.Sheets(mySheetNames).Delete

    're-enable the display of alerts and messages
    Application.DisplayAlerts = True

End Sub

Effects of Executing Macro Example to Delete Multiple Sheets

The following GIF illustrates the results of executing the macro example. The (i) the first 2 sheets (Sheet6 and Sheet7), and (ii) the sheets named “delete multiple sheets 1” and “delete multiple sheets 2”, are deleted.

Macro deletes multiple sheets

References to VBA Constructs Used in this VBA Tutorial

Use the following links to visit the appropriate webpage in the Microsoft Developer Network:

  1. Identify workbook containing sheets, worksheets or chart sheets to delete:
    • Application.ThisWorkbook property.
    • Application.ActiveWorkbook property.
    • Application.Workbooks property.
    • Workbook object.
  2. Identify sheets, worksheets and chart sheets:
    • Workbook.Sheets property.
    • Application.ActiveSheet property.
    • Sheets object.
    • Workbook.Worksheets property.
    • Worksheet object.
    • Workbook.Charts property.
    • Chart object.
  3. Delete sheets, worksheets and chart sheets:
    1. Worksheet.Delete method.
    2. Chart.Delete method.
  4. Prevent Excel from displaying prompts or warnings when deleting a sheet, worksheet or chart sheet:
    • Application.DisplayAlerts property.
  5. Handle errors:
    • On Error statement.
  6. Create an array containing the names of several sheets, worksheets or chart sheets to delete:
    • Array function.
  7. Work with variables and data types:
    • Dim statement.
    • = operator.
    • Data types:
      • Long data type.
      • String data type.
      • Variant data type.

There are times when we have to create or add sheet and later on we found of no use of that sheet, hence we get need to delete sheet quickly from the workbook. This article focus on saving time & provide code for removing sheets without any prompt message box using vba macro / code. It could be one sheet or several.  And excel gives a popup alert to confirm the sheet deletion.  If its one sheet, its manageable.  But if you have to delete several sheets, you will get one popup per sheet.

You often create multiple sheets using VBA. But in the end, you don’t need them actually. You would want to delete them after your work is done. It will keep your file lighter, faster and sensible.

VBA code to delete a sheet is simple

Sheets("SheetName").Delete

Let’s say you have this code to add a sheet and then delete it when work is done.

Sub AddAndDeleteSheet()
Sheets.Add 'Adds a new sheet to the active workbook

'----

'----

'----

'some work on sheet done
ActiveSheet.Delete 'deletes the active Activesheet

End Sub

When you execute this code, Sheets.Add will work without any prompt but when compiler will come to  ActiveSheet.Delete it will prompt a message like this.

pasted image 0 (1)

Since you are deleting sheets using VBA, you know what you are doing. You would like to tell Excel not to show this warning and delete the damn sheet.

To do this we will switch off the display alert button of Excel Application.

The code below will bypass this alert message and the sheet will be deleted without any intimation.

Sub AddAndDeleteSheet()

Application.DisplayAlerts = False 'switching off the alert button
Sheets.Add

'----

'----

'----

'some work on sheet done
ActiveSheet.Delete

Application.DisplayAlerts = True 'switching on the alert button

End Sub

Here we are deleting Activesheet using VBA. You can delete any sheet using VBA. Just write Sheets(«Sheetname»).delete. Moving on…

DisplayAlerts is a property of Application object in VBA. Here we are switching it off at the beginning of our code and switching it on at the end of the code. The above code will confirm deletion without any intimation.

Note:The above code will ignore all the warnings thrown by excel. If you want to allow only sheet deletion than use this line.

Application.DisplayAlerts = False 'switching off the alert button

ActiveSheet.Delete

Application.DisplayAlerts = True 'switching on the alert button

This will ignore only sheet deletion warning.

Pro Tip: This lines of code make your VBA code more efficient. Always use them at the beginning of your macro and turn them back on wherever is your code expected to exit routine.
Warning: If not turned on before exiting the subroutine, you may not see any warning at all. Even if your code is not running. This may cause many problems.

If you have multiple sheets to delete and are using a loop, try this code  –

Option Explicit

Sub macro2()

Dim i As Long

Application.DisplayAlerts = False

For i = 1 to Worksheets.Count

If Worksheets(i).Name Like "Test*" Then Worksheets(i).Delete

Next i

Application.DisplayAlerts = True

End Sub

That’s it. It’s done. It easy like switching your fan on and off. Isn’t it?

image 29

If you liked our blogs, share it with your friends on Facebook. And also you can follow us on Twitter and Facebook.
We would love to hear from you, do let us know how we can improve, complement or innovate our work and make it better for you. Write us at info@exceltip.com

Download file

Delete sheets without confirmation prompts using VBA in Microsoft Excel

Related Articles:

Split Excel Sheet Into Multiple Files Based On Column Using VBA

Change The Default Printer Using VBA in Microsoft Excel 2016

Turn Off Warning Messages Using VBA in Microsoft Excel 2016

Display A Message On The Excel VBA Status Bar

Insert Pictures Using VBA in Microsoft Excel 2016

How To Loop Through Sheets In Excel Using VBA

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity

How to use the VLOOKUP Function in Excel

How to use the COUNTIF function in Excel

How to use the SUMIF Function in Excel

Понравилась статья? Поделить с друзьями:
  • Delete all styles in word
  • Delete all rows in excel vba
  • Delete all references in word
  • Delete all names in excel
  • Delete all macros in word