Vba add sheet in excel

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

Создание, копирование, перемещение и удаление рабочих листов 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, смотрите в этой статье.

This tutorial explains how to add new work sheets using Worksheets.Add Method in Excel VBA, or add new worksheets at the back or before specific worksheet

You may also want to read:

Excel VBA Worksheets.Copy Method to copy worksheet

Excel VBA Worksheets.Add Method is to add new worksheet in a workbook.

Syntax of Excel VBA Worksheets.Add Method

Worksheets.Add([Before],[After],[Count],[Type])
Before Optional. Add new worksheet before specific worksheet
After Optional, add new worksheet after specific worksheet
Count Optional. Number of worksheets to add, default is 1
Type Optional. Worksheet type, default is xlWorksheet

xlWorksheet
xlChart
xlExcel4MacroSheet
xlExcel4IntlMacroSheet

If Before and After are not specified, worksheet is added before Active worksheet (the worksheet you selected before running the Add Method).

Example 1 – Add new worksheet after specific worksheet

The below code add new worksheet after Sheet8

Set newWS = ThisWorkbook.Worksheets.Add(After:=Worksheets("Sheet8"))

Example 2 – Add new worksheet and move to the end of worksheet

The below code makes use of Worksheets(Worksheets.Count) to find the last worksheet. Worksheets(Index) returns the Nth worksheet from left to right.

Set newWS = ThisWorkbook.Worksheets.Add(After:=Worksheets(Worksheets.Count))

Example 3 – Add new worksheet and move to the first worksheet

Set newWS = ThisWorkbook.Worksheets.Add(Before:=Worksheets(1))

Example 4 – add new worksheet if not exist

The below code makes use of a custom Function called wsExist to check if a worksheet already exists, returns TRUE if exists, FALSE if not exist.

Sub createWS()
    Dim ws, newWS As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        If wsExists("worksheet1") Then
           counter = 1
        End If
    Next ws

    If counter = 0 Then
        Set newWS = ThisWorkbook.Worksheets.Add(After:=Worksheets(Worksheets.Count))  
        newWS.Name = "worksheet1"
    End If
End Sub
          
Function wsExists(wksName As String) As Boolean
    On Error Resume Next
    wsExists = CBool(Len(Worksheets(wksName).Name) > 0)
    On Error GoTo 0
End Function

Outbound References

https://msdn.microsoft.com/en-us/library/office/microsoft.office.interop.excel.worksheets.add.aspx?f=255&MSPPError=-2147217396

How to Create a Worksheet in Excel?

MS Office provides option to create dynamic spreadsheet in Excel during run-time.

Also, users can do to other worksheet operations like copy, move, rename and delete though VBA. Let’s begin by creating a new workbook or try downloading the Sample File at end of this topic.

If you want to learn how to do it in simple method, follow these simple steps.

Excel VBA Dynamic Spreadsheet Add – Copy Content

Here is an example, in which we have a list of worksheet names and their content present in single sheet. We are going to add new sheets as mentioned in the list and copy the content to corresponding sheet.

To begin with, create a new workbook and enter the Columns as in below image.

Excel vba Worksheets Add - Create Excel spreadsheet

Excel vba Worksheets Add – Create Excel spreadsheet

The above screenshot has columns as explained below.

  • Column 1: list of Worksheet names to be created dynamically.
  • Column 2 to 4: data to be copies against the sheet name it is mapped.

Sheets.Add After – Excel VBA Create Worksheet

Sheets.Add is the VBA command in Excel create worksheets dynamically during run-time. To perform other worksheet operations, we use the below functions.

  • Add – To add a new sheet
  • Copy – Copy a existing sheet
  • Move – Move the sheet’s order
  • Delete – Delete a sheet

Apart from these functions, below list are some of the useful properties that we use often inside Excel Macro.

  • Name – To get or change the name of a worksheet
  • Count – To get number of worksheets
  • Visible – To make a sheet’s visibility.

To do this, copy paste the below code in Excel VB Editor and execute the code by pressing F5. (If you are new to Excel Macro, refer the Hello World program Blog in this site).

Private Sub CommandButton1_Click()
    Excel_VBA_Add_WorkSheets
End Sub

Private Sub Excel_VBA_Add_WorkSheets()
    'Declaration of Variables
    Dim iRow As Integer
    Dim Rown As Integer
    Dim TabName_Prev As String
    Dim TabName_Curr As String

    'Initialize Variables
    iRow = 1
    Rown = 1
    TabName_Prev = "Test"

    'Excel VBA Create Worksheet
    While Trim(ThisWorkbook.Sheets("Sheet1").Cells(iRow, 1)) <> ""
        iRow = iRow + 1
        TabName_Curr = Trim(ThisWorkbook.Sheets("Sheet1").Cells(iRow, 1))
        If TabName_Curr = "" Then GoTo End_Of_Process_Label

        'Create Sheet
        If TabName_Curr <> TabName_Prev Then
            ThisWorkbook.Sheets("Sheet1").Activate
            Sheets.Add after:=Sheets(Sheets.Count) 'Sheets.Add.Name = "New SheetName" will also work
            On Error Resume Next
            ActiveSheet.Name = TabName_Curr
            Rown = 1
        End If

        'Copy Data To Newly Added Sheet
        Rown = Rown + 1
        ThisWorkbook.Sheets(TabName_Curr).Cells(Rown, 1) = Trim(ThisWorkbook.Sheets("Sheet1").Cells(iRow, 2))
        ThisWorkbook.Sheets(TabName_Curr).Cells(Rown, 2) = Trim(ThisWorkbook.Sheets("Sheet1").Cells(iRow, 3))
        ThisWorkbook.Sheets(TabName_Curr).Cells(Rown, 3) = Trim(ThisWorkbook.Sheets("Sheet1").Cells(iRow, 4))
        TabName_Prev = Trim(ThisWorkbook.Sheets("Sheet1").Cells(iRow, 1))
    Wend

End_Of_Process_Label:
    MsgBox "Excel VBA - Worksheet Added Dynamically - Process Completed"
    Sheets.VPageBreaks
End Sub

Download Sample Excel document with Above Macro : Download 519

Excel VBA Adding Worksheet – Additional Reference

  • http://support.microsoft.com/kb/107622
  • http://stackoverflow.com/questions/3840628/creating-and-naming-worksheet-in-excel-vba

Like this post? Please share to your friends:
  • Vba add shape word
  • Vba excel 2013 книга скачать
  • Vba add row excel vba
  • Vba excel 2010 таблица
  • Vba add button excel