Excel add sheet with name

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

Insert a worksheet

  • Select the New Sheet plus icon Select at the bottom of the workbook.

  • Or, select Home > Insert > Insert Sheet.

    Insert Cells

Rename a worksheet

  • Double-click the sheet name on the Sheet tab to quickly rename it.

  • Or, right-click on the Sheet tab, click Rename, and type a new name.

Move a worksheet

  • To move the tab to the end, right-click the Sheet tab then Move or Copy > (move to end) > OK .

  • Or, click and drag to tab to any spot.

Delete a worksheet

  • Right-click the Sheet tab and select DeleteDelete.

  • Or, select the sheet, and then select Home > Delete > Delete Sheet.

    Delete

Note: Sheet tabs are displayed by default. If you don’t see them, click Options > Advanced > Display options for this workbook > Show Sheet tabs.

To insert a new worksheet, do one of the following:

  • To quickly insert a new worksheet at the end of the existing worksheets, click the Insert Worksheet tab at the bottom of the screen.

    Sheet tabs

  • To insert a new worksheet in front of an existing worksheet, select that worksheet and then, on the Home tab, in the Cells group, click Insert, and then click Insert Sheet.

    The Cells group on the Home tab

    Tip: You can also right-click the tab of an existing worksheet, and then click Insert. On the General tab, click Worksheet, and then click OK.

    Note: To change the order of the worksheets in a workbook, click the tab of the worksheet that you want to move, and then drag it to the location that you want.

What do you want to do?

  • Insert multiple worksheets at the same time

  • Change the default number of worksheets in a new workbook

  • Insert a new sheet that is based on a custom template

  • Rename a worksheet

  • Delete one or more worksheets

Insert multiple worksheets at the same time

  1. Hold down SHIFT, and then select the same number of existing sheet tabs of the worksheets that you want to insert in the open workbook.

    For example, if you want to add three new worksheets, select three sheet tabs of existing worksheets.

  2. On the Home tab, in the Cells group, click Insert, and then click Insert Sheet.

    The Cells group on the Home tab

    Tip: You can also right-click the selected sheet tabs, and then click Insert. On the General tab, click Worksheet, and then click OK.

  3. To change the order of the worksheets in a workbook, click the tab of the worksheet that you want to move, and then drag it to the location that you want.

Change the default number of worksheets in a new workbook

  1. Click the File tab.

    What and where is the Microsoft Backstage Button?

    For more information about the Microsoft Backstage Button, see What and where is the Backstage?

  2. Under Excel, click Options.

  3. In the General category, under When creating new workbooks, in the Include this many sheets box, enter the number of sheets that you want to include by default when you create a new workbook.

  4. Click any other tab to return to your file.

Insert a new sheet that is based on a custom template

  1. If needed, create the worksheet template that you want to base a new worksheet on.

    How to create a worksheet template

    1. Select the worksheet that you want to use as a template.

    2. Click the File tab.

    3. Under Info, click Save As.

    4. In the File name box, type the name of the worksheet template.

      • To create a custom worksheet template, type the file name that you want to use.

      • To create the default worksheet template, type sheet.

        Note: Custom templates are automatically saved in the Templates folder. The default worksheet template, sheet.xltx or sheet.xltm, should be saved in the XLStart folder, which is usually C:Program FilesMicrosoft OfficeOffice14XLStart.

    5. Do one of the following:

      • On a computer that is running Windows Vista, in the list, click Excel Template or Excel Macro-Enabled Template.

      • On a computer that is running Microsoft Windows XP, in the Save as type box, click Excel Template or Excel Macro-Enabled Template.

    6. Click Save.

  2. Right-click the sheet tab of a worksheet, and then click Insert.

  3. Double-click the template for the type of sheet that you want.

Rename a worksheet

  1. On the Sheet tab bar, right-click the sheet tab that you want to rename, and then click Rename Sheet.

    Sheet tabs with Sheet2 selected

  2. Select the current name, and then type the new name.

    Tip: You can include the name of the sheet when you print the worksheet.

    How to print sheet names

    1. On the Insert tab, in the Text group, click Header & Footer.

    2. In the Page Layout View, click the location where you want the sheet name to appear.

    3. In the Header & Footer elements group, click Sheet Name Button image.

Delete one or more worksheets

  1. Select the worksheet or worksheets that you want to delete.

    Tip: When multiple worksheets are selected, [Group] appears in the title bar at the top of the worksheet. To cancel a selection of multiple worksheets in a workbook, click any unselected worksheet. If no unselected sheet is visible, right-click the tab of a selected sheet, and then click Ungroup Sheets on the shortcut menu.

  2. On the Home tab, in the Cells group, click the arrow next to Delete, and then click Delete Sheet.

    The Cells group on the Home tab

    Tip: You can also right-click the sheet tab of a worksheet or a sheet tab of any selected worksheets that you want to delete, and then click Delete Sheet.

Skip to content

Как добавить новый лист и присвоить имя

На чтение 2 мин. Просмотров 6.8k.

Что делает макрос: Самый простой вариант автоматизации — добавить новый лист с присвоением ему конкретного имени.

Содержание

  1. Как макрос работает
  2. Код макроса
  3. Как работает макрос
  4. Как использовать

Как макрос работает

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

Код макроса

Sub DobavitNoviiList()
'Шаг 1: Говорим Excel, что делать, если ошибка
On Error GoTo MyError
'Шаг 2: Добавляем лист
Sheets.Add
'Шаг 3: Присваиваем имя
ActiveSheet.Name = "Отчет"_
WorksheetFunction.Text(Now(),"yyyy")
'Шаг 4: Выходим
Exit Sub
'Шаг 5: Если произошла ошибка, сообщение пользователю
MyError:
MsgBox "Лист с таким именем уже есть!"
End Sub

Как работает макрос

  1. Вы знаете, что если присвоить новому листу имя, которое уже есть, то возникнет ошибка. Таким образом, на шаге 1, макрос говорит Excel немедленно перейти к строке, которая говорит MyError (на шаге 3), если есть ошибка.
  2. Для создания листа используем метод Add. По умолчанию, лист называется SheetХХ, где хх представляет число листа. Мы даем листу новое имя путем изменения свойства объекта ActiveSheet.Name в этом случае мы именуем рабочий лист «Отчёт и текущий год».
  3. Как и в рабочих книгах, каждый раз, когда вы добавляете новый лист с помощью VBA, он автоматически становится активным. Именно поэтому мы пишем ActiveSheet.Name.
  4. Обратите внимание, что на шаге 4 мы выходим из процедуры. Делаем так, чтобы он случайно не показал сообщение об ошибке.
  5. Данный шаг запускается, если имя нового листа совпадает с уже существующим в книге. С помощью сообщения уведомляем пользователя об этом. Опять же, этот шаг должен быть выполнен только в случае возникновения ошибки.

Как использовать

Для реализации этого макроса, вы можете скопировать и вставить его в стандартный модуль:

  1. Активируйте редактор Visual Basic, нажав ALT + F11.
  2. Щелкните правой кнопкой мыши имя проекта / рабочей книги в окне проекта.
  3. Выберите Insert➜Module.
  4. Введите или вставьте код во вновь созданном модуле.

Sometimes, you want to create a new sheet and automatically name it with a specific name in Excel. In this article, we will show you two methods of adding new sheet with specific name in current workbook, as well as creating a worksheet with specific name in a new workbook in Excel.

Auto adding new sheet with specific name in current workbook with VBA code
Auto adding new sheet with specific name in a new workbook with Kutools for Excel


Auto adding new sheet with specific name in current workbook with VBA code

You can add a new sheet with certain name at the end of current workbook with following VBA code.

1. Press Alt + F11 keys simultaneously to open the Microsoft Visual Basic for Applications window.

2. In the Microsoft Visual Basic for Applications window, click Insert > Module.

3. Copy and paste below VBA code into the Module window.

VBA code: add new sheet with specific name at the end of current workbook

Sub CreateSheet()
'Updated by ExtendOffice 20181009
    Dim xName As String
    Dim xSht As Object
    On Error Resume Next
    xName = InputBox("Please enter a name for this new sheet ", "Kutools for Excel")
    If xName = "" Then Exit Sub
        Set xSht = Sheets(xName)
        If Not xSht Is Nothing Then
            MsgBox "Sheet cannot be created as there is already a worksheet with the same name in this workbook"
            Exit Sub
            End If
            Sheets.Add(, Sheets(Sheets.count)).Name = xName
        End Sub

4. Press F5 key to run the code. In the popping up Kutools for Excel dialog box, please enter a name for this sheet, and then click the OK button. See screenshot:

Then a new worksheet is created with specific name and located at the end of current workbook.


Auto adding new sheet with specific name in a new workbook with Kutools for Excel

In this section, we will introduce the Create Sequence Worksheets utility of Kutools for Excel. With this utility, you can easily add new sheet with specific name in a new workbook.

1. For adding new sheet with specific name, you need to type this name into a cell in advance. And then click Kutools Plus > Worksheet > Create Sequence Worksheets.

2. In the Create Sequence Worksheets dialog box, select Blank worksheet in the Base Worksheet drop-down list, select Datain a range option, and specify the cell that contains the certain worksheet name, and finally click the OK button. See screenshot:

Then a new worksheet with this specific name from a cell is created in a new workbook immediately.

Notes:

1. If you want to create multiple new sheets with specific names at the same time, please enter these names in cells one by one, and then select these cells in the Data in a range box.

2. You can also create sequence worksheets from a series numbers or a custom list with this Create Sequence Worksheets utility. See screenshot:

  If you want to have a free trial (30-day) of this utility, please click to download it, and then go to apply the operation according above steps.


The Best Office Productivity Tools

Kutools for Excel Solves Most of Your Problems, and Increases Your Productivity by 80%

  • Reuse: Quickly insert complex formulas, charts and anything that you have used before; Encrypt Cells with password; Create Mailing List and send emails…
  • Super Formula Bar (easily edit multiple lines of text and formula); Reading Layout (easily read and edit large numbers of cells); Paste to Filtered Range
  • Merge Cells/Rows/Columns without losing Data; Split Cells Content; Combine Duplicate Rows/Columns… Prevent Duplicate Cells; Compare Ranges
  • Select Duplicate or Unique Rows; Select Blank Rows (all cells are empty); Super Find and Fuzzy Find in Many Workbooks; Random Select…
  • Exact Copy Multiple Cells without changing formula reference; Auto Create References to Multiple Sheets; Insert Bullets, Check Boxes and more…
  • Extract Text, Add Text, Remove by Position, Remove Space; Create and Print Paging Subtotals; Convert Between Cells Content and Comments
  • Super Filter (save and apply filter schemes to other sheets); Advanced Sort by month/week/day, frequency and more; Special Filter by bold, italic…
  • Combine Workbooks and WorkSheets; Merge Tables based on key columns; Split Data into Multiple Sheets; Batch Convert xls, xlsx and PDF
  • More than 300 powerful features. Supports Office / Excel 2007-2021 and 365. Supports all languages. Easy deploying in your enterprise or organization. Full features 30-day free trial. 60-day money back guarantee.

kte tab 201905


Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!

officetab bottom

Comments (5)


No ratings yet. Be the first to rate!

New Worksheets are continually being added to your Workbook. It might seem incredibly tedious to have to do everything by hand at times (specifically if you have multiple sheets to add).

Automating these monotonous tasks is a quick and easy way to solve the problem.

Using VBA to Add New Worksheet with Specific Name

I have programmed the Visual Basic for Applications (VBA) code to add a new Worksheet at the very end of the Worksheets and give it the label «specific name»

Step 1

Save the file and then go to the Developer menu and pick Visual Basic.

Or,

Simply pressing ALT + F11 will bring up the Visual Basic Editor.

Step 2

To access the project’s workbook, right-click its name in the Project panel

Step 3

In order to access the VBA editor, go to the Insert menu and choose Module.

This is the VBA editor.

Step 4

Enter one of the codes that are listed below into the editing window (based on your requirement)

Sub AddAndNameWithSpecificName()
'Step 1: Tell Excel what to do in the event of an error.
 On Error GoTo Error

'Step 2: Create a new worksheet and give it a name that is
easily identifiable.
 Sheets.Add.Name = "My Specific Name" 'Create a new
worksheet and call it "My Specific Name," then replace "My
New Sheet" with your own name..
 Exit Sub

'Step 3: If there was a problem here, the user should be
informed.
Error:
 MsgBox "That is the name of an existing Worksheet in the
spreadsheet."
End Sub

Put an end to editing in the VBA environment.

To respond to the new sheet, you should make a button.

Step 5

Make a button by selecting the insert option in the developer tab and clicking it.

Step 6

Place the assigned macro script within this button. And press OK.

Step 7

This is the button that has been generated; you may rename it according to your specifications if you want.

in addition to clicking on this button.

Step 8

You may personalise a sheet and give it the name «My Specific Name.» This will cause it to appear in the results automatically

Manually Add New Worksheet with Current Date

Consider the scenario in which you are compiling a record of the time spent on various tasks and want to quickly input the current date. Or you could wish to have the current date shown in a sheet in a way that is triggered automatically whenever the formulae are recalculated. There are a few different approaches one may use when inserting today’s date into a sheet.

Step 1

When you first launch Microsoft Excel, you are presented with a menu that gives you the choice between a number of different worksheets, as is seen below.

Step 2

You have the option of picking one that corresponds to the prerequisites. Make a blank worksheet for the time being. The blank worksheet appears as shown down below.

Step 3

It is possible that you may get into a position in which you will need to append an additional worksheet to the side of the one that is already there. Excel Workbooks are collections of Excel worksheets that are kept together in one location. Right-clicking on the sheet name in the bottom sheet tracker tray allows you to insert a new worksheet into the document. This is shown in the following image.

Step 4

Create a new worksheet like the one shown below by choosing the «new worksheet» option from the list of choices that are now accessible to you.

Step 5

You will see a new dialogue box emerge on the screen, in which you will have the opportunity to pick the option to add a new sheet.

Step 6

You have the ability to give the Excel Worksheet a new name by rightclicking on the sheet’s name and choosing the rename option from the dialogue box, as is shown in the following image.

Step 7

You are free to rename this sheet in current date, for example Sheet1, to current date.

Conclusion

In this tutorial, we explained how you can add a new worksheet with a specific name in Excel.

Понравилась статья? Поделить с друзьями:
  • Excel add on for graphs
  • Excel add sheet at end
  • Excel add numbers with text
  • Excel add ins что это
  • Excel add in vsto