Sheet add after 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 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. VBA Routine to Add and Name Worksheets
  2. Add Sheet
  3. Add Sheet with Name
  4. Create New Sheet with Name from a Cell
  5. Add Sheet Before / After Another Sheet
  6. Insert Sheet After Another Sheet
  7. Add Sheet To End of Workbook
  8. Add Sheet To Beginning of Workbook:
  9. Add Sheet to Variable
  10. More Add Sheet Examples
  11. Create Sheet if it Doesn’t Already Exist
  12. Create Worksheets From List of Names
  13. VBA Coding Made Easy
  14. VBA Code Examples Add-in
  15. How do I add a worksheet after all existing Excel worksheets?
  16. 2 Answers 2
  17. Linked
  18. Related
  19. Hot Network Questions
  20. Subscribe to RSS
  21. How to add a named sheet at the end of all Excel sheets?
  22. 8 Answers 8
  23. Linked
  24. Related
  25. Hot Network Questions
  26. Subscribe to RSS
  27. VBA-Урок 3. Коллекция Sheets
  28. Как посчитать количество листов в книге
  29. Как добавить лист в книгу
  30. Как скрыть лист
  31. VBA Sheets – The Ultimate Guide
  32. Sheets Vs. Worksheets
  33. Referencing Sheets
  34. ActiveSheet
  35. Sheet Name
  36. Sheet Index Number
  37. Sheet Index Number – Last Sheet in Workbook
  38. Sheet “Code Name”
  39. VBA Coding Made Easy
  40. Referencing Sheets in Other Workbooks
  41. Activate vs. Select Sheet
  42. Activate a Sheet
  43. Select a Sheet
  44. Select Multiple Sheets
  45. Worksheet Variable
  46. Loop Through All Sheets in Workbook
  47. Worksheet Protection
  48. Workbook Protection
  49. Worksheet Protection
  50. Protect Worksheet
  51. Unprotect Worksheet
  52. Worksheet Visible Property
  53. Unhide Worksheet
  54. Hide Worksheet
  55. Very Hide Worksheet
  56. Worksheet-Level Events
  57. Worksheet Activate Event
  58. Worksheet Change Event
  59. Worksheet Cheat Sheet
  60. VBA Worksheets Cheatsheet
  61. VBA Code Examples Add-in

VBA Routine to Add and Name Worksheets

In this Article

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

Add Sheet

This simple macro will add a Sheet before the ActiveSheet:

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).

Add Sheet with Name

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

Create New Sheet with Name from a Cell

Or use a cell value to name a new Sheet:

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:

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

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

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:

Add Sheet To Beginning of Workbook:

To add a Sheet to the beginning of the workbook:

Add Sheet to Variable

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

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

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.

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.

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

Then the following sheets will be created:

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

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!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

How do I add a worksheet after all existing Excel worksheets?

I need to add an Excel sheet at the end of the current sheet number 3. When I run the below program, however, I get a sheet at the first position. How can I resolve this?

The program basically copies data from one Excel workbook to another workbook, consisting of multiple sheets.

2 Answers 2

You can add sheets in the After position, ie this code adds the sheet after the last worksheet (provided by objWrkBk.Sheets(objWrkBk.Sheets.Count)) where objWrkBk.Sheets.Count) is the number of sheets prior to the addition.

seems Worksheets property is read-only

Returns a Sheets collection that represents all the worksheets in the specified workbook. Read-only Sheets object.

whereas Sheets is the real thing where you can also add Sheets dynamically

A collection of all the sheets in the specified or active workbook.

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to add a named sheet at the end of all Excel sheets?

I am trying to add an Excel sheet named «Temp» at the end of all existing sheets, but this code is not working:

Can you please let me know why?

8 Answers 8

Or use a With clause to avoid repeatedly calling out your object

Above can be further simplified if you don’t need to call out on the same worksheet in the rest of the code.

Kindly use this one liner:

(when you add a worksheet, anyway it’ll be the active sheet)

If you want to check whether a sheet with the same name already exists, you can create a function:

When the function is created, you can call it from your main Sub, e.g.:

Try switching the order of your code. You must create the worksheet first in order to name it.

This will give you the option to:

  1. Overwrite or Preserve a tab that has the same name.
  2. Place the sheet at End of all tabs or Next to the current tab.
  3. Select your New sheet or the Active one.

This is a quick and simple add of a named tab to the current worksheet:

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

VBA-Урок 3. Коллекция Sheets

Данная коллекция представляет собой набор листов (Sheets) в книге (Workbooks). Давайте посмотрим, какие действия мы можем делать над листами.

Как посчитать количество листов в книге

Сначала попробуем узнать сколько листов имеет наша книга:

Данным кодом мы вызвали сообщения на экран (MsgBox), которое отобразило количество листов (Sheets.Count) в книге (Workbooks) » Test.xls«.

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

Как добавить лист в книгу

В коллекции листов также есть возможность добавлять свои листы, для этого существует метод Add. Этот метод имеет 4 параметра Add (Before, After, Count, Type). Все эти параметры необязательны. Первые два отвечают за место вставки листа. Далее, количество листов, вставляемых Count и тип листа Type . Типы могут быть, например, такие xlWorkSheet для расчетного листа и xlChart для диаграммы. Если местоположение не указывать, то лист будет вставляться относительно текущего листа.

Таким образом мы вставили 4 листа (Count: = 4) после листа «Лист3» .

Также можно вставить лист в самый конец книги:

Как скрыть лист

Если у Вас есть желание, то некоторые листы можно скрыть. Это бывает полезно, если у Вас есть константы или расчеты, которые Вы не хотите чтобы видели на экране в виде листов. Для этого можно использовать метод Visible. Устанавливая это свойство в TRUE или FALSE вы можете убрать или отобразить необходимый лист.

Источник

VBA Sheets – The Ultimate Guide

In this Article

This is the ultimate guide to working with Excel Sheets / Worksheets in VBA.

At the bottom of this guide, we’ve created a cheat sheet of common commands for working with sheets.

Sheets Vs. Worksheets

There are two ways to reference Sheets using VBA. The first is with the Sheets object:

The other is with the Worksheets object:

99% of the time, these two objects are identical. In fact, if you’ve searched online for VBA code examples, you’ve probably seen both objects used. Here is the difference:

The Sheets Collection contains Worksheets AND Chart Sheets.

So use Sheets if you want to include regular Worksheets AND Chart Sheets. Use Worksheets if you want to exclude Chart Sheets. For the rest of this guide we will use Sheets and Worksheets interchangeably.

Referencing Sheets

There are several different ways to reference Sheets:

  • ActiveSheet
  • Sheet Tab Name
  • Sheet Index Number
  • Sheet Code Name

ActiveSheet

The ActiveSheet is the Sheet that’s currently active. In other words, if you paused your code and looked at Excel, it’s the sheet that is visible. The below code example will display a MessageBox with the ActiveSheet name.

Sheet Name

You are probably most familiar with referencing Sheets by their Tab Name:

This is the sheet name that’s visible to Excel users. Enter it into the sheets object, as a string of text, surrounded by quotations.

Sheet Index Number

The Sheet Index number is the sheet position in the workbook. 1 is the first sheet. 2 is the second sheet etc.:

Sheet Index Number – Last Sheet in Workbook

To reference the last Sheet in the workbook, use Sheets.Count to get the last Index Number and activate that sheet:

Sheet “Code Name”

The Sheet Code Name is it’s Object name in VBA:

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!

Referencing Sheets in Other Workbooks

It’s also easy to reference Sheets in other Workbooks. To do so, you need to use the Workbooks Object:

Important: The Workbook must be open before you can reference its Sheets.

Activate vs. Select Sheet

In another article we discuss everything about activating and selecting sheets. The short version is this:

When you Activate a Sheet it becomes the ActiveSheet. This is the sheet you would see if you looked at your Excel program. Only one sheet may be activate at a time.

Activate a Sheet

When you select a Sheet, it also becomes the ActiveSheet. However, you can select multiple sheets at once. When multiple sheets are selected at once, the “top” sheet is the ActiveSheet. However, you can toggle the ActiveSheet within selected sheets.

Select a Sheet

Select Multiple Sheets

Use an array to select multiple sheets at once:

Worksheet Variable

Assigning a worksheet to an object variable allows you to reference the worksheet by it’s variable name. This can save a lot of typing and make your code easier to read. There are also many other reasons you might want to use variables.

To declare a worksheet variable:

Assign a worksheet to a variable:

Now you can reference the worksheet variable in your code:

Loop Through All Sheets in Workbook

Worksheet variables are useful when you want to loop through all the worksheets in a workbook. The easiest way to do this is:

This code will loop through all worksheets in the workbook, displaying each worksheet name in a message box. Looping through all the sheets in a workbook is very useful when locking / unlocking or hiding / unhiding multiple worksheets at once.

Worksheet Protection

Workbook Protection

Workbook protection locks the workbook from structural changes like adding, deleting, moving, or hiding worksheets.

You can turn on workbook protection using VBA:

or disable workbook protection:

Note: You can also protect / unprotect without a password by omitting the Password argument:

Worksheet Protection

Worksheet-level protection prevents changes to individual worksheets.

Protect Worksheet

Unprotect Worksheet

There are a variety of options when protecting worksheets (allow formatting changes, allow user to insert rows, etc.) We recommend using the Macro Recorder to record your desired settings.

We discuss worksheet protection in more detail here.

Worksheet Visible Property

You might already know that worksheets can be hidden:

There are actually three worksheet visibility settings: Visible, Hidden, and VeryHidden. Hidden sheets can be unhidden by any regular Excel user – by right-clicking in the worksheet tab area (shown above). VeryHidden sheets can only be unhidden with VBA code or from within the VBA Editor. Use the following code examples to hide / unhide worksheets:

Unhide Worksheet

Hide Worksheet

Very Hide Worksheet

Worksheet-Level Events

Events are triggers that can cause “Event Procedures” to run. For example, you can cause code to run every time any cell on a worksheet is changed or when a worksheet is activated.

Worksheet event procedures must be placed in a worksheet module:

There are numerous worksheet events. To see a complete list, go to a worksheet module , select “Worksheet” from the first drop-down. Then selecting an event procedure from the second drop-down to insert it into the module.

Worksheet Activate Event

Worksheet activate events run each time the worksheet is opened.

This code will select cell A1 (resetting the view area to the top-left of the worksheet) each time the worksheet is opened.

Worksheet Change Event

Worksheet change events run whenever a cell value is changed on the worksheet. Read our tutorial about Worksheet Change Events for more information.

Worksheet Cheat Sheet

Below you will find a cheat sheet containing common code examples for working with sheets in VBA

VBA Worksheets Cheatsheet

VBA worksheets Cheatsheet

Description Code Example
Referencing and Activating Sheets
Tab Name Sheets(«Input»).Activate
VBA Code Name Sheet1.Activate
Index Position Sheets(1).Activate
Select Sheet
Select Sheet Sheets(«Input»).Select
Set to Variable Dim ws as Worksheet
Set ws = ActiveSheet
Name / Rename ActiveSheet.Name = «NewName»
Next Sheet ActiveSheet.Next.Activate
Loop Through all Sheets Dim ws as Worksheet

For each ws in Worksheets
Msgbox ws.name
Next ws Loop Through Selected Sheets Dim ws As Worksheet

For Each ws In ActiveWindow.SelectedSheets
MsgBox ws.Name
Next ws Get ActiveSheet MsgBox ActiveSheet.Name Add Sheet Sheets.Add Add Sheet and Name Sheets.Add.Name = «NewSheet» Add Sheet With Name From Cell Sheets.Add.Name = range(«a3»).value Add Sheet After Another Sheets.Add After:=Sheets(«Input») Add Sheet After and Name Sheets.Add(After:=Sheets(«Input»)).Name = «NewSheet» Add Sheet Before and Name Sheets.Add(Before:=Sheets(«Input»)).Name = «NewSheet» Add Sheet to End of Workbook Sheets.Add After:=Sheets(Sheets.Count) Add Sheet to Beginning of Workbook Sheets.Add(Before:=Sheets(1)).Name = «FirstSheet» Add Sheet to Variable Dim ws As Worksheet
Set ws = Sheets.Add Copy Worksheets Move Sheet to End of Workbook Sheets(«Sheet1»).Move After:=Sheets(Sheets.Count) To New Workbook Sheets(«Sheet1»).Copy Selected Sheets To New Workbook ActiveWindow.SelectedSheets.Copy Before Another Sheet Sheets(«Sheet1»).Copy Before:=Sheets(«Sheet2») Before First Sheet Sheets(«Sheet1»).Copy Before:=Sheets(1) After Last Sheet Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count) Copy and Name Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = «LastSheet» Copy and Name From Cell Value Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = Range(«A1»).Value To Another Workbook Sheets(«Sheet1»).Copy Before:=Workbooks(«Example.xlsm»).Sheets(1) Hide / Unhide Sheets Hide Sheet Sheets(«Sheet1»).visible = False
or
Sheets(«Sheet1»).visible = xlSheetHidden Unhide Sheet Sheets(«Sheet1»).Visible = True
or
Sheets(«Sheet1»).Visible = xlSheetVisible Very Hide Sheet Sheets(“Sheet1”).Visible = xlSheetVeryHidden Delete or Clear Sheets Delete Sheet Sheets(«Sheet1»).Delete Delete Sheet (Error Handling) On Error Resume Next
Sheets(«Sheet1»).Delete
On Error GoTo 0 Delete Sheet (No Prompt) Application.DisplayAlerts = False
Sheets(«Sheet1»).Delete
Application.DisplayAlerts = True Clear Sheet Sheets(«Sheet1»).Cells.Clear Clear Sheet Contents Only Sheets(«Sheet1»).Cells.ClearContents Clear Sheet UsedRange Sheets(«Sheet1»).UsedRange.Clear Protect or Unprotect Sheets Unprotect (No Password) Sheets(«Sheet1»).Unprotect Unprotect (Password) Sheets(«Sheet1»).Unprotect «Password» Protect (No Password) Sheets(«Sheet1»).Protect Protect (Password) Sheets(«Sheet1»).Protect «Password» Protect but Allow VBA Access Sheets(«Sheet1»).Protect UserInterfaceOnly:=True Unprotect All Sheets Dim ws As Worksheet

For Each ws In Worksheets
ws.Unprotect «password»
Next ws

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

8 ответов

Попробуйте следующее:

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    ws.Name = "Tempo"
End Sub

Или используйте предложение With, чтобы избежать неоднократного вызова вашего объекта

Private Sub CreateSheet()
    Dim ws As Worksheet
    With ThisWorkbook
        Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        ws.Name = "Tempo"
    End With
End Sub

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

Sub CreateSheet()
    With ThisWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
    End With
End Sub

L42
20 дек. 2013, в 07:01

Поделиться

Пожалуйста, используйте этот один вкладыш:

Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name"

Amar
03 янв. 2016, в 06:24

Поделиться

Попробуйте следующее:

Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
    On Error GoTo the_dark

    Dim wsSheet As Worksheet
    Dim bFoundWS As Boolean
    bFoundWS = False
    If inNamePrefix <> "" Then
        Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
    End If

    If inBeforeOrAfter = iAfter Then
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
        Else
            Worksheets.Add(After:=wsSheet).Name = inName
        End If
    Else
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(Before:=Worksheets(1)).Name = inName
        Else
            Worksheets.Add(Before:=wsSheet).Name = inName
        End If
    End If

    Set addSheet = findWS(inWB, inName, bFoundWS)         ' just to confirm it exists and gets it handle

    the_light:
    Exit Function
    the_dark:
    MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
    Err.Clear
    GoTo the_light
End Function

Mr F
07 окт. 2014, в 12:45

Поделиться

ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"

(при добавлении листа, в любом случае это будет активный лист)

Saptarshi
14 сен. 2015, в 09:11

Поделиться

Попробуйте использовать:

Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = "MySheet"

Если вы хотите проверить, существует ли листок с тем же именем, вы можете создать функцию:

Function funcCreateList(argCreateList)
    For Each Worksheet In ThisWorkbook.Worksheets
        If argCreateList = Worksheet.Name Then
            Exit Function ' if found - exit function
        End If
    Next Worksheet
    Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = argCreateList
End Function

Когда функция будет создана, вы можете вызвать ее из основного Sub, например:

Sub main

    funcCreateList "MySheet"

Exit Sub

Ivan Tokarev
23 март 2016, в 10:24

Поделиться

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

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
    ws.Name = "Tempo"
End Sub

спасибо,

Developer
15 нояб. 2016, в 19:44

Поделиться

Это даст вам возможность:

  • Перезаписать или сохранить вкладку с тем же именем.
  • Поместите лист на конец всех вкладок или рядом с текущей вкладкой.
  • Выберите свой новый лист или активный.

Call CreateWorksheet("New", False, False, False)


Sub CreateWorksheet(sheetName, preserveOldSheet, isLastSheet, selectActiveSheet)
  activeSheetNumber = Sheets(ActiveSheet.Name).Index

  If (Evaluate("ISREF('" & sheetName & "'!A1)")) Then 'Does sheet exist?
    If (preserveOldSheet) Then
      MsgBox ("Can not create sheet " + sheetName + ". This sheet exist.")
      Exit Sub
    End If
      Application.DisplayAlerts = False
      Worksheets(sheetName).Delete
    End If

    If (isLastSheet) Then
      Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName 'Place sheet at the end.
    Else 'Place sheet after the active sheet.
      Sheets.Add(After:=Sheets(activeSheetNumber)).Name = sheetName
    End If

    If (selectActiveSheet) Then
      Sheets(activeSheetNumber).Activate
    End If

End Sub

moberme
17 окт. 2017, в 22:40

Поделиться

Это быстрое и простое добавление именованной вкладки к текущему листу:

Sheets.Add.Name = "Tempo"

Jan
22 окт. 2015, в 20:37

Поделиться

Ещё вопросы

  • 0PHP в цикле / цикл по каждому элементу
  • 1Как заменить всю строку во всех столбцах, используя панд?
  • 0POST-запрос к API
  • 1Pandas Convert float column, содержащий значения nan, в int для операции слияния
  • 0Не удается нарисовать спрайт изображения с DirectX9 из Direct2D PNG
  • 1Удалить n из словаря Python
  • 1Создать фрейм данных с использованием кортежей
  • 0jquery ajaxForm извлекает поля внутри скрытого div
  • 1Как запустить таймер в приложении напоминания
  • 0Восстановление Docker не удалось
  • 0C ++ создать новый массив чисел
  • 1Сериализация дерева объектов Java в пользовательский XML
  • 1Pandas категорических данных: хранение преобразования
  • 0Поиск фильтра AngularJS вообще не работает
  • 0Проблемы с передачей файла с сервера на другой сервер
  • 0Использование $ routeParams внутри фильтра повторов
  • 1Зум D3 постоянно уменьшает и уменьшает SVG, как мне это исправить?
  • 1Проблема с SSL при установке любого пакета с использованием pip за прокси
  • 0Когда я устанавливаю сайт phpfox, он показывает мне надоедливую ошибку кодирования языка
  • 1ProgressDialog не отображается в AsyncTask
  • 0После запроса не возвращайте строку с NULL с mySQL
  • 0Переименуйте индекс с помощью миграции сиквела.
  • 0Сделать текстовое поле недоступным для редактирования и не только для чтения
  • 0PHP переменная выполнения не определена в блоке try, который устанавливает оператор prepare
  • 0Получение записей без соответствующих записей в объединенной таблице
  • 0Получите доступ к значению HTML-тега с несколькими кнопками, имеющего значение класса, созданное в PHP и получающее в JavaScript
  • 0Выход execlp () не может быть перенаправлен на стандартный вывод с конвейером
  • 1Java — целостность текстовых документов
  • 0MySQL Выберите СУММУ Итого Транзакции
  • 0В доступе XAMPP отказано для Require_Once Mac OS X Yosemite
  • 1Android-версия среднего уровня AVAudioPlayerPowerForChannel
  • 0изменить div с фоновым изображением на цвет фона с переходом влево
  • 0преобразовать сервис на завод в AngularJS
  • 1Удалить специальный символ из строки
  • 1Значок запуска приложения неверен
  • 0Ошибка динамического параллелизма CUDA: LNK2001
  • 1Unity перетащить игровой объект (например, спрайт) с помощью мыши
  • 0Как я могу добавить обратный вызов с элементом формы для загрузки файла с использованием JavaScript и Httphandler
  • 1Как правильно настроить Datadog со Slack?
  • 0почему мой код jquery не работает в мобильном браузере
  • 0Объединение таблиц с отдельным диапазоном дат без наложения данных — Доступ
  • 1Intent Bundle каждый раз возвращает Null? [Дубликат]
  • 1Как проверить, содержит ли файл строки, которые будут повторять двойной знак?
  • 0прерывание выполнения с помощью Visual Studio / Qt
  • 0MySQLi зацикливание запроса по массиву возвращает throws Неопределенное смещение: 1
  • 1График не отображается должным образом
  • 0печать объекта, хранящегося в массиве, используя jquery
  • 1Vue.js: отключение кнопки на родительском компоненте в зависимости от состояния дочернего компонента
  • 1Цвет строки списка активности Android в зависимости от состояния объекта
  • 1Найдите совпадение в строке файла, затем перейдите к следующему файлу

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

I am trying to add an Excel sheet named «Temp» at the end of all existing sheets, but this code is not working:

Private Sub CreateSheet()
    Dim ws As Worksheet
    ws.Name = "Tempo"
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
End Sub

Can you please let me know why?

ZygD's user avatar

ZygD

21k39 gold badges77 silver badges98 bronze badges

asked Dec 20, 2013 at 6:33

Behseini's user avatar

1

Try this:

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    ws.Name = "Tempo"
End Sub

Or use a With clause to avoid repeatedly calling out your object

Private Sub CreateSheet()
    Dim ws As Worksheet
    With ThisWorkbook
        Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        ws.Name = "Tempo"
    End With
End Sub

Above can be further simplified if you don’t need to call out on the same worksheet in the rest of the code.

Sub CreateSheet()
    With ThisWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
    End With
End Sub

answered Dec 20, 2013 at 6:39

L42's user avatar

L42L42

19.3k11 gold badges43 silver badges68 bronze badges

5

Kindly use this one liner:

Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name"

answered Jan 3, 2016 at 5:27

Amar's user avatar

AmarAmar

4294 silver badges6 bronze badges

2

ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"

(when you add a worksheet, anyway it’ll be the active sheet)

answered Sep 14, 2015 at 7:56

Saptarshi's user avatar

SaptarshiSaptarshi

1252 silver badges3 bronze badges

Try this:

Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
    On Error GoTo the_dark

    Dim wsSheet As Worksheet
    Dim bFoundWS As Boolean
    bFoundWS = False
    If inNamePrefix <> "" Then
        Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
    End If

    If inBeforeOrAfter = iAfter Then
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
        Else
            Worksheets.Add(After:=wsSheet).Name = inName
        End If
    Else
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(Before:=Worksheets(1)).Name = inName
        Else
            Worksheets.Add(Before:=wsSheet).Name = inName
        End If
    End If

    Set addSheet = findWS(inWB, inName, bFoundWS)         ' just to confirm it exists and gets it handle

    the_light:
    Exit Function
    the_dark:
    MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
    Err.Clear
    GoTo the_light
End Function

JF it's user avatar

JF it

2,4033 gold badges20 silver badges30 bronze badges

answered Oct 7, 2014 at 12:44

Mr F's user avatar

Mr FMr F

511 silver badge1 bronze badge

Try to use:

Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = "MySheet"

If you want to check whether a sheet with the same name already exists, you can create a function:

Function funcCreateList(argCreateList)
    For Each Worksheet In ThisWorkbook.Worksheets
        If argCreateList = Worksheet.Name Then
            Exit Function ' if found - exit function
        End If
    Next Worksheet
    Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = argCreateList
End Function

When the function is created, you can call it from your main Sub, e.g.:

Sub main

    funcCreateList "MySheet"

Exit Sub

answered Mar 23, 2016 at 10:14

Ivan Tokarev's user avatar

Try switching the order of your code. You must create the worksheet first in order to name it.

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
    ws.Name = "Tempo"
End Sub

thanks,

answered Nov 15, 2016 at 19:04

Developer's user avatar

DeveloperDeveloper

7417 silver badges12 bronze badges

This will give you the option to:

  1. Overwrite or Preserve a tab that has the same name.
  2. Place the sheet at End of all tabs or Next to the current tab.
  3. Select your New sheet or the Active one.

Call CreateWorksheet("New", False, False, False)


Sub CreateWorksheet(sheetName, preserveOldSheet, isLastSheet, selectActiveSheet)
  activeSheetNumber = Sheets(ActiveSheet.Name).Index

  If (Evaluate("ISREF('" & sheetName & "'!A1)")) Then 'Does sheet exist?
    If (preserveOldSheet) Then
      MsgBox ("Can not create sheet " + sheetName + ". This sheet exist.")
      Exit Sub
    End If
      Application.DisplayAlerts = False
      Worksheets(sheetName).Delete
    End If

    If (isLastSheet) Then
      Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName 'Place sheet at the end.
    Else 'Place sheet after the active sheet.
      Sheets.Add(After:=Sheets(activeSheetNumber)).Name = sheetName
    End If

    If (selectActiveSheet) Then
      Sheets(activeSheetNumber).Activate
    End If

End Sub

answered Oct 17, 2017 at 22:19

moberme's user avatar

mobermemoberme

6597 silver badges13 bronze badges

This is a quick and simple add of a named tab to the current worksheet:

Sheets.Add.Name = "Tempo"

rink.attendant.6's user avatar

answered Oct 22, 2015 at 19:04

Jan's user avatar

JanJan

4113 silver badges9 bronze badges

How to insert a single Excel worksheet after a specific sheet using Excel, VBA and Shortcut methods

METHOD 1. Insert an Excel worksheet after a specific sheet using the New sheet button option

EXCEL

Select a sheet after which you want to insert a new worksheet > Click New sheet button

1. Select the sheet after which you want to insert a new worksheet.
2. Click on the New sheet button.
Note: in this example a new worksheet will be inserted after Sheet2, given we have selected Sheet2.
Select a specific sheet and click on the New sheet button - Excel

METHOD 1. Insert an Excel worksheet after a specific sheet using VBA

VBA

Sub Insert_Worksheet_After_a_Specific_Sheet()

‘insert a new worksheet after a sheet named Sheet2
Worksheets.Add After:=Sheets(«Sheet2»)

End Sub

PREREQUISITES
Sheet Name: Have a sheet named Sheet2, this can be either a worksheet or a chart sheet.

ADJUSTABLE PARAMETERS
Sheet Name: Select the sheet after which you want to insert a new worksheet by changing the Sheet2 sheet name in the VBA code to any sheet in the workbook.

METHOD 2. Insert an Excel worksheet after a specific worksheet using VBA

VBA

Sub Insert_Worksheet_After_a_Specific_Worksheet()

‘insert a new worksheet after a worksheet named Sheet2
Worksheets.Add After:=Worksheets(«Sheet2»)

End Sub

PREREQUISITES
Worksheet Name: Have a worksheet named Sheet2.

ADJUSTABLE PARAMETERS
Worksheet Name: Select the worksheet after which you want to insert a new worksheet by changing the Sheet2 worksheet name in the VBA code to any worksheet in the workbook.

METHOD 3. Insert an Excel worksheet after a specific chart sheet using VBA

VBA

Sub Insert_Worksheet_After_a_Specific_Chart_Sheet()

‘insert a new worksheet after a chart sheet named Analysis Chart
Worksheets.Add After:=Charts(«Analysis Chart»)

End Sub

PREREQUISITES
Chart Sheet Name: Have a chart sheet named Analysis Chart.

ADJUSTABLE PARAMETERS
Chart Sheet Name: Select the chart sheet after which you want to insert a new worksheet by changing the Analysis Chart chart sheet name in the VBA code to any chart sheet in the workbook.

Insert a new worksheet after a specific sheet using a Shortcut

SHORTCUT

WINDOWS SHORTCUT

NOTES
The shortcut will insert a new worksheet in front of an active sheet. Therefore, to insert a new worksheet after a specific sheet you need to activate (select) the sheet to the right of where you want to insert a new worksheet and then action the shortcut.

Explanation about how to insert a worksheet after a specific sheet

EXPLANATION

EXPLANATION
This tutorial explains and provides step by step instructions on how to insert a single worksheet after a specific sheet using using Excel, VBA and Shortcut methods.

Excel Methods: Using Excel you can insert a new worksheet after a specific sheet with the New sheet button.

VBA Methods: Using VBA you can insert a new worksheet after a specific sheet, worksheet or chart sheet by referencing to a Sheets, Worksheets or Charts object, respectively. If you intend to insert a worksheet after a specific worksheet or a chart sheet you will need to have at least one worksheet or chart sheet, respectively, in a workbook.

Shortcut Method: Using a Shortcut in this tutorial you can insert a new worksheet after a specific sheet by activating (selecting) the sheet to the right of where you want to insert a new worksheet and actioning the shortcut.

ADDITIONAL NOTES
Note 1: Using the New sheet button, a new worksheet will be inserted after an active sheet.

Related Topic Description Related Topic and Description
Insert multiple Excel worksheets How to insert multiple Excel worksheets at the same time using Excel, VBA and Shortcut methods
Insert an Excel worksheet How to insert a single Excel worksheet using Excel, VBA and Shortcut methods
Insert an Excel worksheet as the last sheet How to insert a single Excel worksheet as the last sheet using Excel and VBA methods
Insert an Excel worksheet as the first sheet How to insert a single Excel worksheet as the first sheet using Excel, VBA and Shortcut methods
Insert an Excel worksheet before a specific sheet How to insert a single Excel worksheet before a specific sheet using Excel, VBA and Shortcut methods

Понравилась статья? Поделить с друзьями:
  • Short sentences with word like
  • She word of tiger
  • Short sentences with word have
  • She word of horse
  • Short sentences with word because