Vba excel удалить лист по имени

Создание, копирование, перемещение и удаление рабочих листов Excel с помощью кода VBA. Методы Sheets.Add, Worksheet.Copy, Worksheet.Move и Worksheet.Delete.

Создание новых листов

Создание новых рабочих листов осуществляется с помощью метода Sheets.Add.

Синтаксис метода Sheets.Add

expression.Add [Before, After, Count, Type]

где expression — переменная, представляющая собой объект Sheet.

Компоненты метода Sheets.Add

  • Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет добавлен новый.
  • After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет добавлен новый.
  • Count — необязательный параметр типа данных Variant, указывающий, сколько листов будет добавлено (по умолчанию — 1).
  • Type — необязательный параметр типа данных Variant, указывающий тип листа: xlWorksheet** (рабочий лист) или xlChart (диаграмма), по умолчанию — xlWorksheet.

*Если Before и After не указаны, новый лист, по умолчанию, будет добавлен перед активным листом.

**Для создания рабочего листа (xlWorksheet) можно использовать метод Worksheets.Add, который для создания диаграмм уже не подойдет.

Примеры создания листов

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

‘Создание рабочего листа:

Sheets.Add

Worksheets.Add

ThisWorkbook.Sheets.Add After:=ActiveSheet, Count:=2

Workbooks(«Книга1.xlsm»).Sheets.Add After:=Лист1

Workbooks(«Книга1.xlsm»).Sheets.Add After:=Worksheets(1)

Workbooks(«Книга1.xlsm»).Sheets.Add After:=Worksheets(«Лист1»)

‘Создание нового листа с заданным именем:

Workbooks(«Книга1.xlsm»).Sheets.Add.Name = «Мой новый лист»

‘Создание диаграммы:

Sheets.Add Type:=xlChart

‘Добавление нового листа перед

‘последним листом рабочей книги

Sheets.Add Before:=Sheets(Sheets.Count)

‘Добавление нового листа в конец

Sheets.Add After:=Sheets(Sheets.Count)

  • Лист1 в After:=Лист1 — это уникальное имя листа, указанное в проводнике редактора VBA без скобок.
  • Лист1 в After:=Worksheets(«Лист1») — это имя на ярлыке листа, указанное в проводнике редактора VBA в скобках.

Создаваемый лист можно присвоить объектной переменной:

Dim myList As Object

‘В активной книге

Set myList = Worksheets.Add

‘В книге «Книга1.xlsm»

Set myList = Workbooks(«Книга1.xlsm»).Worksheets.Add

‘Работаем с переменной

myList.Name = «Listok1»

myList.Cells(1, 1) = myList.Name

‘Очищаем переменную

Set myList = Nothing

Если создаваемый лист присваивается объектной переменной, он будет помещен перед активным листом. Указать дополнительные параметры невозможно.

Копирование листов

Копирование рабочих листов осуществляется с помощью метода Worksheet.Copy.

Синтаксис метода Worksheet.Copy

expression.Copy [Before, After]

где expression — переменная, представляющая собой объект Worksheet.

Компоненты метода Worksheet.Copy

  • Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет добавлена копия.
  • After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет добавлена копия.

*Если Before и After не указаны, Excel создаст новую книгу и поместит копию листа в нее. Если скопированный лист содержит код в проекте VBA (в модуле листа), он тоже будет перенесен в новую книгу.

Примеры копирования листов

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

‘В пределах активной книги

‘(уникальные имена листов)

Лист1.Copy After:=Лист2

‘В пределах активной книги

‘(имена листов на ярлычках)

Worksheets(«Лист1»).Copy Before:=Worksheets(«Лист2»)

‘Вставить копию в конец

Лист1.Copy After:=Sheets(Sheets.Count)

‘Из одной книги в другую

Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Copy _

After:=Workbooks(«Книга2.xlsm»).Worksheets(«Лист1»)

‘Один лист активной книги в новую книгу

Лист1.Copy

‘Несколько листов активной книги в новую книгу*

Sheets(Array(«Лист1», «Лист2», «Лист3»)).Copy

‘Все листы книги с кодом в новую книгу

ThisWorkbook.Worksheets.Copy

* Если при копировании в новую книгу нескольких листов хотя бы один лист содержит умную таблицу — копирование невозможно. Один лист, содержащий умную таблицу, копируется в новую книгу без проблем.

Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.

Перемещение листов

Перемещение рабочих листов осуществляется с помощью метода Worksheet.Move.

Синтаксис метода Worksheet.Move

expression.Move [Before, After]

где expression — переменная, представляющая собой объект Worksheet.

Компоненты метода Worksheet.Move

  • Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет размещен перемещаемый лист.
  • After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет размещен перемещаемый лист.

*Если Before и After не указаны, Excel создаст новую книгу и переместит лист в нее.

Примеры перемещения листов

Простые примеры перемещения листов:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

‘В пределах активной книги

‘(уникальные имена листов)

Лист1.Move After:=Лист2

‘В пределах активной книги

‘(имена листов на ярлычках)

Worksheets(«Лист1»).Move Before:=Worksheets(«Лист2»)

‘Размещение после последнего листа:

Лист1.Move After:=Sheets(Sheets.Count)

‘Из одной книги в другую

Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Move _

After:=Workbooks(«Книга2.xlsm»).Worksheets(«Лист1»)

‘В новую книгу

Лист1.Move

Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.

Перемещение листа «Лист4» в позицию перед листом, указанным как по порядковому номеру, так и по имени ярлыка:

Sub Peremeshcheniye()

Dim x

x = InputBox(«Введите имя или номер листа», «Перемещение листа «Лист4»»)

If IsNumeric(x) Then x = CLng(x)

Sheets(«Лист4»).Move Before:=Sheets(x)

End Sub

Удаление листов

Удаление рабочих листов осуществляется с помощью метода Worksheet.Delete

Синтаксис метода Worksheet.Delete

expression.Delete

где expression — переменная, представляющая собой объект Worksheet.

Примеры удаления листов

‘По уникальному имени

Лист1.Delete

‘По имени на ярлычке

Worksheets(«Лист1»).Delete

‘По индексу листа

Worksheets(1).Delete

‘В другой книге

Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Delete

Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.

Как обратиться к рабочему листу, переименовать, скрыть или отобразить его с помощью кода VBA Excel, смотрите в этой статье.

 

Greendumb

Пользователь

Сообщений: 26
Регистрация: 11.05.2017

#1

22.05.2017 10:17:34

Здравствуйте!
Есть книга в которой за год помесячно вносятся данные на отдельные листы с соответствующими именами «01.16», «02.16» и т.д.
В конце года данные с указанных листов собираются на один лист с помощью функций макроса.

Код
For Each sh In ActiveWorkbook.Sheets
If sh.Name Like "*.16" Then
    sh.Range("A:H").Copy
    Sheets("2016").Select
    ActiveCell.Offset(0, 10).Select
    ActiveSheet.Paste
End If
Next 

Каким образом можно удалить листы с которых собраны данные?
Заранее благодарю за ответы.

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#2

22.05.2017 10:25:37

Попробуйте такой код.

Код
For Each sh In ActiveWorkbook.Sheets
If sh.Name Like "*.16" Then
    sh.Range("A:H").Copy
    Sheets("2016").Select
    ActiveCell.Offset(0, 10).Select
    ActiveSheet.Paste
    sh.Delete
End If
Next

Изменено: Nordheim22.05.2017 10:31:13

«Все гениальное просто, а все простое гениально!!!»

 

Ivan.kh

Пользователь

Сообщений: 2024
Регистрация: 04.03.2013

#3

22.05.2017 10:36:14

Код
For Each sh In ActiveWorkbook.Sheets
If sh.Name Like "*.16" Then
    sh.Delete
End If
Next

проще после сбора их удалить

Изменено: Ivan.kh22.05.2017 10:37:14

 

Greendumb

Пользователь

Сообщений: 26
Регистрация: 11.05.2017

#4

22.05.2017 10:43:06

Спасибо за ответы!
Обернул цикл в

Код
application.displayalerts = false
...
application.displayalerts = true 

и все работает «без вопросов»)

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

#5

22.05.2017 10:49:07

На будущее, для быстроты работы не используйте Select и Activate? в тех местах где их можно
опустить заменив объекты переменными. В этом случае и инструкция типа

Код
Application.ScreenUpdating

не нужна будет :)

Изменено: Nordheim22.05.2017 10:49:23

«Все гениальное просто, а все простое гениально!!!»

Home / VBA / How to DELETE a SHEET using VBA in Excel

To delete a sheet using VBA, you need to use the VBA Delete method. You need to specify the sheet that you want to delete and then use this method. Let’s say if you want to delete the “Sheet1”, then you need to mention sheet1 and then type a dot (.) and in the end, type “Delete”.

In this tutorial, we will see different ways that you can use to delete a sheet using a VBA code. Make sure to have the developer tab on the ribbon from here you can get into the visual basic editor.

Delete a Sheet using its Name

Each sheet has a name, and you can use write a code to delete a sheet using the name. So, let’s say you want to delete the worksheet “Data”, the code would be:

Sub vba_delete_sheet()
Sheets("Data").Delete
End Sub
  • When you delete a worksheet, Excel shows a message to confirm if you want to remove it or wish to cancel. And when you use a VBA code, in that case, Excel will also do that.

To deal with this, you can turn OFF the screen updating to delete a sheet and then turn it ON.

Application.DisplayAlerts = False
Sheets("Data").Delete
Application.DisplayAlerts = True

Now let’s say you want to use a cell value to use the name of the worksheet. In that case, you need to use the VBA range object to do that.

Delete the Sheet using the Sheet Number

That’s right. You can use the sheet’s number to delete it. Here’s the code.

Sub vba_delete_sheet()
Sheets(1).Delete
End Sub

Delete the ActiveSheet

To delete the active sheet, you can use the “ActiveSheet” object instead of using the sheet name to specify the sheet.

ActiveSheet.Delete

As I said, it deletes the active sheet, and you can activate it before removing it. But necessarily, you don’t need to do that as you can refer to a sheet and delete it as we have seen at the start of this tutorial.

Check if Sheet Exists before Deleting

You can also write code in a way that it can check if the sheet exists or not and then deletes it.

Sub check_sheet_delete()
Dim ws As Worksheet
Dim mySheet As Variant
mySheet = InputBox("enter sheet name")
Application.DisplayAlerts = False
For Each ws In ThisWorkbook.Worksheets
    If mySheet = ws.Name Then
      ws.Delete
    End If
Next ws
Application.DisplayAlerts = True
End Sub

In this code, you have FOR EACH to loop through all the worksheets. And then, an IF STATEMENT to delete the sheet if its name is equal to the name you have typed in the input box.

Delete All the Worksheets in Workbook

I’m sure you have this question in your mind, but I’m afraid it’s impossible to delete all the worksheets that you have in the workbook. You must have at least one worksheet left.

But I have found a solution to this problem. You can insert a new sheet that’s a blank one and then delete all which are already there.

Here’s the code: This code adds a new sheet and deletes all the other sheets.

Sub vba_delete_all_worksheets()
Dim ws As Worksheet
Dim mySheet As String
mySheet = "BlankSheet-" & Format(Now, "SS")
Sheets.Add.Name = mySheet
Application.DisplayAlerts = False
For Each ws In ThisWorkbook.Worksheets
    If ws.Name <> mySheet Then
      ws.Delete
    End If
Next ws
Application.DisplayAlerts = True
End Sub

More Tutorials on VBA Worksheets

  • Back to VBA Worksheet / VBA Tutorial

    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.

    Содержание:

    1. Удаление листов с помощью параметров правой кнопки мыши
    2. Сочетания клавиш для удаления рабочих листов
    3. Гибридная комбинация клавиш для удаления листа
    4. Обычное сочетание клавиш для удаления листа
    5. Устаревшее сочетание клавиш для удаления листов
    6. Удаление ActiveSheet с помощью VBA
    7. Удаление листа без отображения запроса на подтверждение
    8. Удаление листа по имени (если он существует) с помощью VBA
    9. Удаление всех листов, кроме активного листа, с помощью VBA
    10. Удалить все листы с определенной текстовой строкой в ​​имени

    При работе с Excel вы проводите большую часть своего времени на листе (который представляет собой область, в которой находятся все ячейки и все, что там происходит).

    Эффективная работа с Excel также означает, что вам придется работать с несколькими листами в одной книге.

    Excel позволяет легко добавлять несколько листов в книгу, и в то же время вы также можете легко удалить эти листы.

    В этом руководстве по Excel я покажу вам, как быстро удалить листы в Excel. Я бы рассмотрел несколько методов, таких как использование сочетаний клавиш, параметры на ленте и VBA для удаления листов в Excel.

    Примечание. В этом руководстве я буду использовать слова «лист» и «лист» как синонимы. Но чтобы сказать вам разницу, листы будут включать в себя рабочие листы, а также листы диаграмм, но поскольку листы диаграмм не так широко используются, всякий раз, когда я использую слово лист, рассматривайте его как рабочий лист.

    Удаление листов с помощью параметров правой кнопки мыши

    Самый простой способ удалить рабочий лист в Excel — использовать эту простую технику двойного щелчка мыши.

    Предположим, у вас есть рабочий лист с тремя листами, как показано ниже, и вы хотите удалить Sheet1.

    Ниже приведены шаги для этого:

    1. Щелкните правой кнопкой мыши лист, который вы хотите удалить.
    2. Нажмите на опцию удаления
    3. В появившейся подсказке нажмите кнопку Удалить.

    Вы также можете использовать описанную выше технику для листов, которые даже не являются активными. Например, если я сейчас нахожусь на Sheet1 и хочу удалить Shee3, я могу просто щелкнуть правой кнопкой мыши Sheet3 и удалить его.

    Вы также можете использовать ту же технику для удалить сразу несколько листов.

    Например, если я хочу удалить Sheet2 и Sheet3 за один раз, я могу удерживать контрольную клавишу и нажимать Sheet2 и Sheet3 один за другим (при этом все еще удерживая контрольную клавишу).

    Удерживая контрольную клавишу, Excel позволит мне выбрать сразу несколько листов. Когда я закончу выбирать нужные листы, я могу оставить контрольную клавишу. теперь я могу щелкнуть правой кнопкой мыши любую из выбранных вкладок листов и нажать «Удалить».

    Помните, что вы не можете удалить все листы в книге в Excel. в книге всегда должен быть хотя бы один лист. если вы попытаетесь удалить все рабочие листы (или единственный активный лист), вы увидите сообщение о том, что вам не разрешено это делать

    Сочетания клавиш для удаления рабочих листов

    Существует не одна комбинация клавиш, а две с половиной, которые можно использовать для удаления листов в Excel.

    Я говорю «два с половиной», потому что в одном из сочетаний клавиш он использует мышь и клавиатуру (и это все еще более быстрый способ сделать это).

    Гибридная комбинация клавиш для удаления листа

    Щелкните правой кнопкой мыши + D
    Чтобы удалить выбранный рабочий лист или рабочие листы, щелкните правой кнопкой мыши, а затем нажмите клавишу D на клавиатуре.

    Лично я считаю, что это намного быстрее, чем просто удаление листа с помощью мыши (как я уже говорил в предыдущем разделе).

    Обычное сочетание клавиш для удаления листа

    ALT + H + D + S
    Если вы предпочитаете отказаться от мыши и использовать только клавиатуру, указанное выше сочетание клавиш удалит активный лист или выбранные листы.

    Вам нужно нажимать эти клавиши последовательно (т. Е. Одну за другой).

    Хотя это может выглядеть как немного более длинное сочетание клавиш, как только вы привыкнете к нему, оно будет таким же быстрым, как и любой другой метод, описанный в этом руководстве.

    Устаревшее сочетание клавиш для удаления листов

    Как и у всех остальных, у Excel тоже есть прошлое, и оно не такое уж красивое. Я говорю об эпохе до-ленточного стиля.

    По соображениям совместимости Excel по-прежнему позволяет некоторым из этих старых сочетаний клавиш работать в более новых версиях. и во многих случаях эти ранние ярлыки короче и лучше.

    К счастью, есть устаревшее сочетание клавиш, которое работает для удаления листов в Excel.
    ALT + E + L

    Удаление ActiveSheet с помощью VBA

    Когда дело доходит до удаления одного листа или нескольких рабочих листов, лучше использовать вышеупомянутые методы.

    Хотя VBA может автоматизировать процесс, он полезен, когда вам приходится повторять задачу несколько раз.

    Как вы увидите, с помощью VBA вы можете намного больше, когда дело доходит до удаления листов в Excel.

    Итак, я расскажу вам о более сложных случаях использования, но перед этим давайте посмотрим, как просто удалить активный рабочий лист с помощью VBA.

    Ниже приведен код VBA, который удалит активный лист:
    Sub DeleteSheet () ActiveSheet.Delete End Sub
    Если вы используете его в непосредственном окне, вы можете просто использовать следующую строку:
    ActiveSheet.Delete
    Когда вы используете приведенный выше код для удаления активного листа, Excel покажет вам приглашение, в котором вам нужно будет нажать кнопку удаления, чтобы подтвердить действие.

    Удаление листа без отображения запроса на подтверждение

    Окно сообщения с запросом подтверждения — это полезная функция, которая гарантирует, что у вас есть возможность отменить удаление листа в случае, если вы случайно / ошибочно запустили код.

    Но если вы уже знаете, что делаете, это сообщение может сильно раздражать.

    Итак, вот код VBA, который гарантирует, что листы удалены, но вы не видите окно с запросом подтверждения.
    Sub DeleteSheet () Application.DisplayAlerts = False ActiveSheet.Delete Application.DisplayAlerts = True End Sub
    В приведенном выше коде я установил для свойства Application.DisplayAlerts значение false, что означает, что Excel не будет показывать вам какие-либо предупреждения на дисплее во время выполнения кода.

    Также очень важно убедиться, что вы вернули его к истине в конце кода, чтобы восстановить функциональность (как вы можете видеть, что я сделал в приведенном выше коде).

    Внимание! Если для свойства Application.DisplayAlerts установлено значение false, Excel просто удалит рабочий лист, и восстановить его будет невозможно. поэтому я советую вам сделать резервную копию, прежде чем использовать такой код.

    Удаление листа по имени (если он существует) с помощью VBA

    VBA позволяет автоматизировать процесс удаления определенного листа (на нескольких листах) на основе имени листа.

    Например, если у вас есть рабочий лист с названием «Продажи», вы можете использовать приведенный ниже код, чтобы удалить его:
    Sub DeleteSheetByName () Sheets ("Продажи"). Удалить End Sub
    Этот код удалит только лист с именем «Продажи».

    Это полезно, когда у вас есть рабочая тетрадь с большим количеством листов, и вы не хотите просматривать все листы, найдите тот, у которого есть имя продажи, и удалите его вручную.

    С приведенным выше кодом не имеет значения, сколько листов в книге, он просто удалит рабочий лист.

    И поскольку я не менял свойство Application.DisplayAlert, вы увидите приглашение, в котором вам нужно будет нажать кнопку удаления, чтобы подтвердить продолжительность листа продаж.

    Если вы хотите удалить несколько листов по их имени, вы также можете это сделать.

    Например, приведенный ниже код удалит листы с именами Продажи, Маркетинг, Финансы:
    Sub DeleteSheetsByName () Sheets («Продажи»). Delete Sheets («Marketing»). Delete Sheets («Finance»). Delete End Sub

    Удаление всех листов, кроме активного листа, с помощью VBA

    Если у вас есть книга с несколькими листами, и вы хотите удалить все листы, кроме активного листа, VBA, вероятно, является одним из лучших способов сделать это.

    Ниже приведен код VBA, который удалит все листы, кроме активного листа в книге.
    Sub DeleteSheetByName () Dim ws As Worksheet Application.DisplayAlerts = False для каждого ws в таблицах Если ws.Name ActiveSheet.Name Then ws.Delete End If Next ws Application.DisplayAlerts = True End Sub
    Обратите внимание, что я сказал, что свойство Application.DisplayAlerts находится в начале кода, так как я не хочу видеть подсказку для каждого удаляемого листа.

    Удалить все листы с определенной текстовой строкой в ​​имени

    Это немного более продвинутый вариант эффективного использования VBA при удалении листов.

    Предположим, у вас есть книга с множеством разных листов, и вы хотите удалить все листы, в которых есть определенная текстовая строка, тогда вы можете легко сделать это с помощью VBA.

    Например, ниже у меня есть рабочая книга, в которой я хочу удалить все рабочие листы, в которых есть текстовая строка «Продажи».

    Ниже приведен код VBA, который сделает это:
    Sub DeleteSheetByName () Dim ws As Worksheet Application.DisplayAlerts = False For Each ws In Sheets If ws.Name Like "*" & "Sales" & "*" Тогда MsgBox ws.Name ws.Delete End If Next ws Application.DisplayAlerts = Истинный конец Sub
    В приведенном выше коде используется оператор if-then для просмотра всех листов в книге. Он проверяет имя всех этих рабочих листов, и если имя содержит слово «Продажи», то этот рабочий лист удаляется.

    Если вы хотите изменить код и найти любую другую текстовую строку, вы можете изменить ее в пятой строке приведенного выше кода.

    Также обратите внимание, что я использовал звездочку (*), которая является символом подстановки, с обеих сторон текстовой строки, которую мы ищем в имени рабочего листа. Это гарантирует, что независимо от того, где строка появляется в имени листа, она все равно будет удалена.

    Вы также можете изменить код, чтобы убедиться, что удаляются только те рабочие листы, где текстовая строка появляется в начале имени рабочего листа.

    Например, если вы хотите удалить те листы, в которых термин продажи появляется в начале, используйте следующий код в пятой строке.
    Если ws.Name Like "*" & "Sales" & "*" Тогда
    Здесь я использовал подстановочный знак только после текста «drink», а не перед ним. Это обеспечит при проверке имен рабочего листа только те, которые будут соответствовать критериям, в которых термин «Продажи» стоит в начале имени.

    Итак, это некоторые из методов, которые вы можете использовать, если хотите удалить листы в Excel. В большинстве случаев вы можете легко сделать это прямо на рабочем листе с помощью мыши или сочетания клавиш.

    Но если у вас тяжелая книга с большим количеством листов и вы хотите быстро удалить определенные типы листов, вы также можете использовать VBA.

    Надеюсь, вы нашли этот урок полезным.

    Понравилась статья? Поделить с друзьями:
  • Vba excel удалить комментарии
  • Vba excel файлы примеров
  • Vba excel удалить колонки
  • Vba excel удалить значения ячеек
  • Vba excel удалить все пустые строки в excel