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, смотрите в этой статье.

In this guide, we’re going to show you how to create and name a worksheet with VBA in Excel.

Download Workbook

Syntax

You can create and name a worksheet using the Sheets.Add and Worksheets.Add methods. Both methods work similarly and have 4 optional arguments and return a sheet object which can take a Name property.

Sheets.Add ([Before], [After], [Count], [Type])

Worksheets.Add ([Before], [After], [Count], [Type])

Name Description
Before Optional. The sheet before which the new sheet is to be added.
If omitted, Excel creates the new sheet(s) before the selected sheet(s).
After Optional. The sheet after which the new sheet is added.
If omitted, Excel creates the new sheet(s) before the selected sheet(s).
Count The number of sheets to be added.
The default is the number of selected sheets.
Type Specifies the sheet type.
The default is xlWorksheet which represents a standard worksheet.

Adding a single sheet

All arguments are optional. The method without arguments creates worksheet(s) equal to the number of selected worksheets before the first selected worksheet.

Sheets.Add

For example, if two sheets are selected, the method will add two worksheets. To ignore the selected sheets and set the sheet number to one (1), use 1 for the Count argument.

Sheets.Add Count:=1

Adding multiple sheets

You can set the Count argument to an integer greater than 1 to add multiple sheets at once. For example, the following code adds three (3) worksheets.

Sheets.Add Count:=3

Adding a sheet with a name

Sheets.Add method returns a sheet object and sets its name by updating the Name property. A property is an attribute of object that determines one of the object’s characteristics. The property of an object is addressed by entering the property name after the corresponding object and a dot(.). Just like calling the Add method for the Sheets object.

If all you need is to create worksheets and name them regardless of their position, use one of the following code lines.

Sheets.Add.Name = “My Sheet”
Sheets.Add(Count:=1).Name = “My Sheet” ‘Use this line to ensure creating a single sheet

Adding a sheet before or after a specific sheet

If the new sheet’s position is important, use either the Before or After argument. Each argument accepts a sheet object. The new sheet will be created before or after the sheet you supplied based on the argument you are using.

You can call a sheet object by giving the sheet’s name or index to Sheets or Worksheets objects. It can be a variable which you have defined. Here are some examples:

Sheets.Add Before:=Worksheets("My Sheet") ‘Add sheet(s) before “My Sheet”
Sheets.Add After:=Worksheets(3) ‘Add sheet(s) after the third sheet
Dim ws As Worksheet ‘Define a new worksheet object
Set ws = Sheets.Add ‘Create and assign new sheet to the worksheet object
Sheets.Add After:=ws ‘Add a new sheet after the recently added sheet (ws)

Creating and naming multiple worksheets

To name multiple worksheets, you have to use an array of names and a loop. Let’s say you have names in a range like A1:A5 in the worksheet named “Sheet1”. A loop should check each cell inside the range and create a worksheet from the corresponding name. Check out the following code:

 Sub CreateAndNameMultipleSheets()
    Dim rng As Range 'Range object which defines a cell
    For Each rng In Sheets("Sheet1").Range("A1:A5")
        Sheets.Add.Name = rng.Value
    Next
End Sub

This is our last tip for how to create and name a worksheet with VBA in Excel article. If you are new to loops in VBA, check out All You Need to Know on How to Create a VBA loop in Excel to understand and find more ways of looping.

Once you start learning VBA one of the coolest things you can do is to write a VBA code to insert new a worksheet in a workbook.

Well, there is already a shortcut key to insert a new worksheet or you can also use the normal option but the benefit of using a VBA code is you can add multiple worksheets with a single click and you can also define that where you want to add it.

For this, you need to use the Sheets.Add method, and in this post, we will be learning how to use it to add one or more worksheets in a workbook.

Sheets.Add Method

Sheets.Add ([Before], [After], [Count], [Type])
  • Before: To add a new sheet before a sheet.
  • After: To add the new sheet before a sheet.
  • Count: Number of sheets to add.
  • Type: Type of the sheet you want to add (LINK)

Open the visual basic editor and follow these steps.

  • First, you need to enter Sheets.Add method.
  • Then you need to define the place to add the new sheet (Before or After).
  • Next thing is to enter the count of worksheets.
  • In the end, the type of sheet.

Different Ways to Add New Sheets in a Workbook using a VBA Code

Below you have different ways to add a new sheet to a workbook:

1. Add a Single Sheet

To add a single sheet, you can use the below code, where you didn’t specify any argument.

Sub SheetAddExample1()
ActiveWorkbook.Sheets.Add
End Sub

This code tells Excel to add a sheet in the active workbook, but as you don’t have any argument it will use the default values and add one worksheet(xlWorksheet) before the active sheet.

Here’s one more way to write this, check out the below code.

Sub SheetAddExample2()
Sheets.Add
End Sub

As you are already in the active workbook you can use the below code as well. It does the same thing.

2. Add Multiple Sheets

To add multiple sheets in one go, you just need to define the COUNT argument with the number of sheets you want to add.

Sub AddSheets3()
Sheets.Add Count:=5
End Sub

Now the count of the sheets that you have defined is 5, so when you run this code it instantly adds the five new sheets in the workbook.

3. Add a Sheet with a Name

If you want to rename the sheet after adding it, you can use the following code:

Sub AddNewSheetswithNameExample1()
Sheets.Add.Name = "myNewSHeet"
End Sub

In the above code, we have used the name object (LINK) which helps you to specify the name of a sheet.

4. Add a Sheet with a Name from a Cell

You can also take the value to use as the sheet’s name from a cell.

Sub AddNewSheetswithNameExample2()
Sheets.Add.Name = Range("A1")
End Sub

In the above code, cell A1 is used to get the name for the new sheet.

5. Add a Sheet After/Before a Specific Sheet

As these arguments are already there in the Sheets.Add where you can specify the sheet to add a new sheet before or after it.

Sub AddSheetsExample5()
Sheets.Add Before:=Worksheets("mySheet")
Sheets.Add After:=Worksheets("mySheet")
End Sub

Now in the above code, you have two lines of code that you have used before and after an argument in the Sheet.Add method. So, when you run this code it adds two sheets one is before and one is after the “mySheet”.

6. Add a New Sheet at Beginning

By using the before argument using you can also add a sheet at the beginning of the sheets that you have in the workbook.

So basically, what we are going to do is we’re going to specify the sheet number instead of the sheet name.

Sub AddSheetsExample6()
Sheets.Add Before:=Sheets(1)
End Sub

In the above code, you have used sheet number (1) that tells VBA to add the sheet before the sheet which is in the first position in all the worksheets. In this way, it will always add the new sheet at the beginning.

7. Add a New Sheet at the End (After the Last Sheet)

To add a new sheet in the end you need to write the code in a different way. So, for this, you need to know how many sheets there in the workbook are so that you can add a new sheet at the end.

Sub AddSheetsExample8()
Sheets.Add After:=Sheets(Sheets.Count)
End Sub

In the above code, Sheet.Count returns the count of the sheets that you have in the workbook, and as you have defined the after argument it adds the new sheet after the last sheet in the workbook.

8. Add Multiple Sheets and use Names from a Range

The following code counts rows from the range A1:A7. After that, it loops to add sheets according to the count from the range and uses values from the range to name the sheet while adding it.

Sub AddSheetsExample9()

Dim sheets_count As Integer
Dim sheet_name As String
Dim i As Integer

sheet_count = Range("A1:A7").Rows.Count

For i = 1 To sheet_count
  sheet_name = Sheets("mySheet").Range("A1:A7").Cells(i, 1).Value
  Worksheets.Add().Name = sheet_name
Next i

End Sub

But with the above code, there could be a chance that the sheet name you want to add already exists or you have a blank cell in the name range.

In that case, you need to write a code that can verify if the sheet with the same name already exists or not and whether the cell from where you want to take the sheet name is blank or not.

If both conditions are fulfilled only then it should add a new sheet. Let me put it in steps two steps:

First, you need to write an Excel User Defined Function to check if a sheet with the same name already exists or not.

Function SheetCheck(sheet_name As String) As Boolean

Dim ws As Worksheet

SheetCheck = False
 
For Each ws In ThisWorkbook.Worksheets
 
    If ws.Name = sheet_name Then
    
        SheetCheck = True
        
    End If
 
Next
 
End Function

Second, you need to write a code using this function and that code should also check if the name cell is blank or not.

Sub AddMultipleSheet2()

Dim sheets_count As Integer
Dim sheet_name As String
Dim i As Integer

sheet_count = Range("A1:A7").Rows.Count

For i = 1 To sheet_count

    sheet_name = Sheets("mySheet").Range("A1:A10").Cells(i, 1).Value
    
    If SheetCheck(sheet_name) = False And sheet_name <> "" Then
    Worksheets.Add().Name = sheet_name
    End If

Next i

End Sub

Now in the above code, you have used the VBA IF Statement and in this statement, you have the sheet check function which checks for the sheet name and then you have a condition to check if the name cell has a blank value.

Sample File

More Tutorials on Worksheets

  • VBA Worksheet – Excel VBA Examples – VBA Tutorial

In this Article

  • Add Sheet
  • Add Sheet with Name
    • Create New Sheet with Name from a Cell
  • Add Sheet Before / After Another Sheet
    • Insert Sheet After Another Sheet
    • Add Sheet To End of Workbook
    • Add Sheet To Beginning of Workbook:
  • Add Sheet to Variable
  • More Add Sheet Examples
    • Create Sheet if it Doesn’t Already Exist
    • Create Worksheets From List of Names
  • VBA Coding Made Easy

This tutorial will discuss how to add / insert worksheets using VBA.

This simple macro will add a Sheet before the ActiveSheet:

Sub Add ()
    Sheets.Add
End Sub

After inserting a Sheet, the new Sheet becomes the ActiveSheet. You can then use the ActiveSheet object to work with the new Sheet (At the bottom of this article we will show how to insert a new sheet directly to a variable).

ActiveSheet.Name = "NewSheet"

Add Sheet with Name

You can also define a Sheet name as you create the new Sheet:

Sheets.Add.Name = "NewSheet"

Create New Sheet with Name from a Cell

Or use a cell value to name a new Sheet:

Sheets.Add.Name = range("a3").value

Add Sheet Before / After Another Sheet

You might also want to choose the location of where the new Sheet will be inserted. You can use the After or Before properties to insert a sheet to a specific location in the workbook.

Insert Sheet After Another Sheet

This code will insert the new sheet AFTER another sheet:

Sheets.Add After:=Sheets("Input")

This will insert a new Sheet AFTER another sheet and specify the Sheet name:

Sheets.Add(After:=Sheets("Input")).Name = "NewSheet"

Notice the extra parenthesis required in the second example (the first example will generate an error if the second parenthesis are added).

or Before:

Sheets.Add(Before:=Sheets("Input")).Name = "NewSheet"

In these examples we explicitly named the Sheet used to determine the sheet location. Often you’ll want to use the Sheet Index number instead, so that you can insert the sheet to the beginning or end of the Workbook:

Add Sheet To End of Workbook

To add a Sheet to the end of the workbook:

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

Add Sheet To Beginning of Workbook:

To add a Sheet to the beginning of the workbook:

Sheets.Add(Before:=Sheets(1)).Name = "FirstSheet"

Add Sheet to Variable

This code assigns the new Sheet to a variable as the sheet is created:

Dim ws As Worksheet
Set ws = Sheets.Add

From here you can reference the new sheet with the variable ‘ws’:

ws.name = "VarSheet"

More Add Sheet Examples

Create Sheet if it Doesn’t Already Exist

You might want to create a sheet only if it doesn’t already exist.

VBA Programming | Code Generator does work for you!

Create Worksheets From List of Names

The following routine will look at the contents of a single column set up Excel worksheets within the current workbook with these names. It makes a call to another function to see if a sheet with that name already exists, and if so the sheet isn’t created.

Private Sub CommandButton1_Click()

Call CreateWorksheets(Sheets("Sheet2").Range("A1:a10"))

End Sub

Sub CreateWorksheets(Names_Of_Sheets As Range)
Dim No_Of_Sheets_to_be_Added As Integer
Dim Sheet_Name As String
Dim i As Integer

No_Of_Sheets_to_be_Added = Names_Of_Sheets.Rows.Count

For i = 1 To No_Of_Sheets_to_be_Added

Sheet_Name = Names_Of_Sheets.Cells(i, 1).Value

'Only add sheet if it doesn't exist already and the name is longer than zero characters

If (Sheet_Exists(Sheet_Name) = False) And (Sheet_Name <> "") Then
    Worksheets.Add().Name = Sheet_Name
End If

Next i

End Sub
Function Sheet_Exists(WorkSheet_Name As String) As Boolean
Dim Work_sheet As Worksheet

Sheet_Exists = False

For Each Work_sheet In ThisWorkbook.Worksheets

    If Work_sheet.Name = WorkSheet_Name Then
        Sheet_Exists = True
    End If

Next

End Function

So if we have the following text in cells A1:A30 in Sheet 2:

adding sheets

Then the following sheets will be created:

adding sheets 2

Note that although “Dog” appears twice, only one sheet is created.

To download the .XLS file for this tutorial, click here.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

Learn More!

<<Return to VBA Examples

Содержание

  1. Sheets.Add method (Excel)
  2. Syntax
  3. Parameters
  4. Return value
  5. Remarks
  6. Example
  7. Support and feedback
  8. Метод Sheets.Add (Excel)
  9. Синтаксис
  10. Параметры
  11. Возвращаемое значение
  12. Примечания
  13. Пример
  14. Поддержка и обратная связь
  15. Создание или замена листа
  16. Определение наличия листа
  17. Создание листа
  18. Замена листа
  19. Об участнике
  20. Поддержка и обратная связь
  21. Метод Worksheets.Add (Excel)
  22. Синтаксис
  23. Параметры
  24. Возвращаемое значение
  25. Примечания
  26. Поддержка и обратная связь

Sheets.Add method (Excel)

Creates a new worksheet, chart, or macro sheet. The new worksheet becomes the active sheet.

Syntax

expression A variable that represents a Sheets object.

Parameters

Name Required/Optional Data type Description
Before Optional Variant An object that specifies the sheet before which the new sheet is added.
After Optional Variant An object that specifies the sheet after which the new sheet is added.
Count Optional Variant The number of sheets to be added. The default value is the number of selected sheets.
Type Optional Variant Specifies the sheet type. Can be one of the following XlSheetType constants: xlWorksheet, xlChart, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If you are inserting a sheet based on an existing template, specify the path to the template. The default value is xlWorksheet.

Return value

An Object value that represents the new worksheet, chart, or macro sheet.

If Before and After are both omitted, the new sheet is inserted before the active sheet.

Example

This example inserts a new worksheet before the last worksheet in the active workbook.

This example inserts a new worksheet after the last worksheet in the active workbook, and captures the returned object reference in a local variable.

In 32-bit Excel 2010, this method cannot create more than 255 sheets at one time.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Метод Sheets.Add (Excel)

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

Синтаксис

expression. Add (Before, After, Count, Type)

выражение: переменная, представляющая объект Sheets.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Before Необязательный Variant Объект, указывающий лист, перед которым добавляется новый лист.
After Необязательный Variant Объект, указывающий лист, после которого добавляется новый лист.
Count Необязательный Variant Количество добавляемых листов. Значение по умолчанию — количество выбранных листов.
Type Необязательный Variant Определяет тип листа. Может быть одной из следующих констант XlSheetType : xlWorksheet, xlChart, xlExcel4MacroSheet или xlExcel4IntlMacroSheet. Если вставляется лист на основе существующего шаблона, укажите путь к шаблону. Значение по умолчанию — xlWorksheet.

Возвращаемое значение

Значение Object, представляющее новый рабочий лист, лист диаграммы или макроса.

Примечания

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

Пример

В этом примере новый лист вставляется перед последним листом в активной книге.

В этом примере новый лист вставляется после последнего листа в активной книге и записывается возвращенная ссылка на объект в локальной переменной.

В 32-разрядной версии Excel 2010 этот метод может создать не более 255 листов за один раз.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Создание или замена листа

В следующих примерах показано, как определить, существует ли лист, а затем создать или заменить его.

Пример кода предоставил: Том Уртис, Atlas Programming Management

Определение наличия листа

В этом примере показано, как определить, существует ли лист с именем Sheet4 с помощью свойства Name объекта Worksheet . Имя листа задается переменной mySheetName .

Создание листа

В этом примере показано, как определить, существует ли лист с именем Sheet4. Имя листа задается переменной mySheetName . Если лист не существует, в этом примере показано, как создать лист с именем Sheet4 с помощью метода Add объекта Worksheets .

Замена листа

В этом примере показано, как определить, существует ли лист с именем Sheet4. Имя листа задается переменной mySheetName . Если лист существует, в этом примере показано, как удалить существующий лист с помощью метода Delete объекта Worksheet , а затем создать новый лист с именем Sheet4.

Важно При удалении листа удаляются все данные на исходном листе с именем Sheet4.

Об участнике

Том Уртис, MVP — основатель компании Atlas Programming Management, создающей полноценные бизнес-решения для Microsoft Office и Excel в Кремниевой долине. Том обладает больше чем 25 годами опыта управления бизнесом и разработки приложений для Microsoft Office, а также является соавтором книги «Holy Macro! It’s 2,500 Excel VBA Examples».

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Метод Worksheets.Add (Excel)

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

Синтаксис

expression. Add (Before, After, Count, Type)

Выражение Переменная, представляющая объект Worksheets .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Before Необязательный Variant Объект, указывающий лист, перед которым добавляется новый лист.
After Необязательный Variant Объект, указывающий лист, после которого добавляется новый лист.
Count Необязательный Variant Количество добавляемых листов. Значение по умолчанию — один.
Type Необязательный Variant Определяет тип листа. Может быть одной из следующих констант XlSheetType : xlWorksheet, xlChart, xlExcel4MacroSheet или xlExcel4IntlMacroSheet. Если вставляется лист на основе существующего шаблона, укажите путь к шаблону. Значение по умолчанию — xlWorksheet.

Возвращаемое значение

Значение Object, представляющее новый рабочий лист, лист диаграммы или макроса.

Примечания

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

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

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