Создание, копирование, перемещение и удаление рабочих листов 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, смотрите в этой статье.
So, what I want to do, generally, is make a copy of a workbook. However, the source workbook is running my macros, and I want it to make an identical copy of itself, but without the macros. I feel like there should be a simple way to do this with VBA, but have yet to find it. I am considering copying the sheets one by one to the new workbook, which I will create. How would I do this? Is there a better way?
asked Jul 28, 2011 at 18:34
1
I would like to slightly rewrite keytarhero’s response:
Sub CopyWorkbook()
Dim sh as Worksheet, wb as workbook
Set wb = workbooks("Target workbook")
For Each sh in workbooks("source workbook").Worksheets
sh.Copy After:=wb.Sheets(wb.sheets.count)
Next sh
End Sub
Edit: You can also build an array of sheet names and copy that at once.
Workbooks("source workbook").Worksheets(Array("sheet1","sheet2")).Copy _
After:=wb.Sheets(wb.sheets.count)
Note: copying a sheet from an XLS? to an XLS will result into an error. The opposite works fine (XLS to XLSX)
answered Jul 28, 2011 at 21:05
iDevlopiDevlop
24.6k11 gold badges89 silver badges147 bronze badges
3
Someone over at Ozgrid answered a similar question. Basically, you just copy each sheet one at a time from Workbook1 to Workbook2.
Sub CopyWorkbook()
Dim currentSheet as Worksheet
Dim sheetIndex as Integer
sheetIndex = 1
For Each currentSheet in Worksheets
Windows("SOURCE WORKBOOK").Activate
currentSheet.Select
currentSheet.Copy Before:=Workbooks("TARGET WORKBOOK").Sheets(sheetIndex)
sheetIndex = sheetIndex + 1
Next currentSheet
End Sub
Disclaimer: I haven’t tried this code out and instead just adopted the linked example to your problem. If nothing else, it should lead you towards your intended solution.
answered Jul 28, 2011 at 19:05
Chris FlynnChris Flynn
9536 silver badges11 bronze badges
2
You could saveAs xlsx. Then you will loose the macros and generate a new workbook with a little less work.
ThisWorkbook.saveas Filename:=NewFileNameWithPath, Format:=xlOpenXMLWorkbook
answered Jul 28, 2011 at 20:55
BradBrad
11.9k4 gold badges44 silver badges70 bronze badges
2
I was able to copy all the sheets in a workbook that had a vba app running, to a new workbook w/o the app macros, with:
ActiveWorkbook.Sheets.Copy
answered Feb 28, 2014 at 17:50
Assuming all your macros are in modules, maybe this link will help. After copying the workbook, just iterate over each module and delete it
answered Jul 28, 2011 at 18:59
ravenraven
4376 silver badges17 bronze badges
Try this instead.
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Copy
Next
ZygD
21k39 gold badges77 silver badges98 bronze badges
answered Jan 17, 2013 at 21:28
You can simply write
Worksheets.Copy
in lieu of running a cycle.
By default the worksheet collection is reproduced in a new workbook.
It is proven to function in 2010 version of XL.
iDevlop
24.6k11 gold badges89 silver badges147 bronze badges
answered Feb 17, 2015 at 14:25
Hors2forceHors2force
1011 silver badge2 bronze badges
Workbooks.Open Filename:="Path(Ex: C:ReportsClientWiseReport.xls)"ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
answered Feb 22, 2013 at 11:39
Here is one you might like it uses the Windows FileDialog(msoFileDialogFilePicker) to browse to a closed workbook on your desktop, then copies all of the worksheets to your open workbook:
Sub CopyWorkBookFullv2()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim x As Integer
Dim closedBook As Workbook
Dim cell As Range
Dim numSheets As Integer
Dim LString As String
Dim LArray() As String
Dim dashpos As Long
Dim FileName As String
numSheets = 0
For Each ws In Application.ActiveWorkbook.Worksheets
If ws.Name <> "Sheet1" Then
Sheets.Add.Name = "Sheet1"
End If
Next
Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFilePicker)
Dim MyString As String
fileExplorer.AllowMultiSelect = False
With fileExplorer
If .Show = -1 Then 'Any file is selected
MyString = .SelectedItems.Item(1)
Else ' else dialog is cancelled
MsgBox "You have cancelled the dialogue"
[filePath] = "" ' when cancelled set blank as file path.
End If
End With
LString = Range("A1").Value
dashpos = InStr(1, LString, "") + 1
LArray = Split(LString, "")
'MsgBox LArray(dashpos - 1)
FileName = LArray(dashpos)
strFileName = CreateObject("WScript.Shell").specialfolders("Desktop") & "" & FileName
Set closedBook = Workbooks.Open(strFileName)
closedBook.Application.ScreenUpdating = False
numSheets = closedBook.Sheets.Count
For x = 1 To numSheets
closedBook.Sheets(x).Copy After:=ThisWorkbook.Sheets(1)
x = x + 1
If x = numSheets Then
GoTo 1000
End If
Next
1000
closedBook.Application.ScreenUpdating = True
closedBook.Close
Application.ScreenUpdating = True
End Sub
answered Apr 5, 2020 at 22:26
try this one
Sub Get_Data_From_File()
'Note: In the Regional Project that's coming up we learn how to import data from multiple Excel workbooks
' Also see BONUS sub procedure below (Bonus_Get_Data_From_File_InputBox()) that expands on this by inlcuding an input box
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
'copy data from A1 to E20 from first sheet
OpenBook.Sheets(1).Range("A1:E20").Copy
ThisWorkbook.Worksheets("SelectFile").Range("A10").PasteSpecial xlPasteValues
OpenBook.Close False
End If
Application.ScreenUpdating = True
End Sub
or this one:
Get_Data_From_File_InputBox()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim ShName As String
Dim Sh As Worksheet
On Error GoTo Handle:
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*.xls*")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
ShName = Application.InputBox("Enter the sheet name to copy", "Enter the sheet name to copy")
For Each Sh In OpenBook.Worksheets
If UCase(Sh.Name) Like "*" & UCase(ShName) & "*" Then
ShName = Sh.Name
End If
Next Sh
'copy data from the specified sheet to this workbook - updae range as you see fit
OpenBook.Sheets(ShName).Range("A1:CF1100").Copy
ThisWorkbook.ActiveSheet.Range("A10").PasteSpecial xlPasteValues
OpenBook.Close False
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
Handle:
If Err.Number = 9 Then
MsgBox «The sheet name does not exist. Please check spelling»
Else
MsgBox «An error has occurred.»
End If
OpenBook.Close False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
both work as
answered Jul 6, 2020 at 4:26
Содержание
- Метод Sheets.Copy (Excel)
- Синтаксис
- Параметры
- Замечания
- Пример
- Поддержка и обратная связь
- Метод Worksheet.Copy (Excel)
- Синтаксис
- Параметры
- Замечания
- Пример
- Поддержка и обратная связь
- Макрос для копирования листа в Excel c любым количеством копий
- Как макросом скопировать листы в Excel
- Описание кода макроса для копирования листов Excel
- Sheets.Copy method (Excel)
- Syntax
- Parameters
- Remarks
- Example
- Support and feedback
- How to duplicate sheet in Excel with VBA
- Excel VBA to copy sheet to new workbook
- Copy multiple sheets in Excel with VBA
- Excel VBA to copy sheet to another workbook
- Copy sheet to the beginning of another workbook
- Copy sheet to the end of another workbook
- Copy sheet to a selected workbook
- Excel macro to copy sheet and rename
- Excel macro to copy sheet and rename based on cell value
- Macro to copy worksheet to a closed workbook
- Excel VBA to copy sheet from another workbook without opening
- Excel VBA to duplicate sheet multiple times
- How to duplicate sheets in Excel with VBA
- How to add a macro to your workbook
- How to run a macro from our sample workbook
- You may also be interested in
Метод Sheets.Copy (Excel)
Копирует лист в другое место в книге.
Синтаксис
expression. Копирование (до, после)
выражение: переменная, представляющая объект Sheets.
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
Before | Необязательный | Variant | Лист, перед которым будет размещен скопированный лист. Невозможно указать параметр Before , если указать After. |
After | Необязательный | Variant | Лист, после которого будет размещен скопированный лист. Вы не можете указать After , если укажем значение До. |
Замечания
Если не указать значение «До» или «После», Microsoft Excel создает новую книгу, содержащую скопированный лист.
Пример
В этом примере выполняется копирование Sheet1, помещая его после Sheet3.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Метод Worksheet.Copy (Excel)
Копирует лист в другое место в текущей или новой книге.
Синтаксис
expression. Копирование (до, после)
Выражение Переменная, представляющая объект Worksheet .
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
Before | Необязательный | Variant | Лист, перед которым будет размещен скопированный лист. Невозможно указать параметр Before , если указать After. |
After | Необязательный | Variant | Лист, после которого будет размещен скопированный лист. Вы не можете указать After , если укажем значение До. |
Замечания
Если не указать значение «До» или «После», Microsoft Excel создает новую книгу, содержащую скопированный объект Worksheet . Только что созданная книга содержит свойство Application.ActiveWorkbook и содержит один лист. На одном листе сохраняются свойства Name и CodeName исходного листа. Если скопированный лист содержал лист кода листа в проекте VBA, он также переносится в новую книгу.
Выбор массива из нескольких листов можно скопировать в новый пустой объект Workbook аналогичным образом.
Источник и назначение должны находиться в одном экземпляре Excel.Application. В противном случае возникает ошибка среды выполнения 1004: не поддерживается такой интерфейс, если использовался что-то подобное Sheet1.Copy objWb.Sheets(1) , или ошибка среды выполнения 1004: сбой метода копирования класса Worksheet, если использовалось что-то подобное ThisWorkbook.Worksheets(«Sheet1»).Copy objWb.Sheets(1) .
Пример
В этом примере выполняется копирование Sheet1, помещая его после Sheet3.
В этом примере сначала файл Sheet1 копируется в новую пустую книгу, а затем сохраняет и закрывает новую книгу.
В этом примере листы Sheet1, Sheet2 и Sheet4 копируются в новую пустую книгу, а затем сохраняются и закрываются.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Макрос для копирования листа в Excel c любым количеством копий
Возможности макросов в Excel практически неограниченные. В данном примере покажем в пару кликов можно создать любое количество копий листов используя VBA-макрос.
Как макросом скопировать листы в Excel
Допустим необходимо приготовить планы работ для сотрудников вашего отдела. Иметься шаблон таблицы для заполнения документа плана в виде одного рабочего листа Excel:
Но вам необходимо создать 12 планов и соответственно 12 листов. В программе Excel нет встроенного инструмента для многократного создания копий рабочих листов за одну операцию. А копировать и вставлять 12 (а в практике встречаются случаи что и 120) листов вручную, да еще их все нужно переименовать – это потребует много рабочего времени и пользовательских сил. Определенно лучше в таком случае воспользоваться собственным макросом. А чтобы его написать воспользуйтесь VBA-кодом, который будет представлен ниже в данной статье.
Сначала откройте редактор макросов Visual Basic:
Создайте в нем стандартный модуль с помощью опций меню: «Insert»-«Module» и введите в него этот код, который ниже представленный на листинге:
Sub CopyList()
Dim kolvo As Variant
Dim i As Long
Dim list As Worksheet
kolvo = InputBox( «Укажите необходимое количество копий для данного листа» )
If kolvo = «» Then Exit Sub
If IsNumeric(kolvo) Then
kolvo = Fix(kolvo)
Set list = ActiveSheet
For i = 1 To kolvo
list.Copy after:=ActiveSheet
ActiveSheet.Name = list.Name & i
Next
Else
MsgBox «Неправильно указано количество»
End If
End Sub
Теперь если нам нужно скопировать 12 (или любое другое количество) раз листов содержащие шаблон для заполнения плана работы сотрудника, кликните по исходному листу, чтобы сделать его активным и выберите инструмент: «РАЗРАБОТЧИК»-«Код»-«Макросы»-«CopyList»-«Выполнить». Сразу после запуска макроса появиться диалоговое окно, в котором следует указать количество копий листа:
Введите, например, число 12 и нажмите ОК:
Лист с шаблоном плана скопируется 12 раз, а все названия листов будут иметь такое же как название исходного листа только со своим порядковым номером от 1 до12.
Внимание! Если название исходного листа слишком длинное, тогда может возникнуть ошибка в процессе выполнения макроса. Ведь в Excel название листа не может содержать более чем 31 символ. То есть ориентируйтесь так чтобы название исходного листа было меньше чем 27 символов. Так же ошибка может возникнуть если текущая рабочая книга Excel уже содержит листы с таким названием как у копий. Ведь в Excel все листы должны иметь уникальные названия.
Примечание. В новых версиях Excel (начиная от 2010 версии) одна рабочая книга может содержать максимальное количество листов, которое ограничивается лишь размером свободной оперативной памяти системы.
Описание кода макроса для копирования листов Excel
В коде используются 3 переменные:
- kolvo – в этой переменной определено какое количество копий будет создано при копировании текущего рабочего листа Excel.
- i – счетчик циклов.
- list – в этой переменной будет создан экземпляр объекта листа Excel.
В начале макроса вызываем диалоговое окно, в котором пользователь должен указать в поле ввода какое количество копий листов необходимо создать с помощью данного макроса «CopyList». Введенное числовое значение в поле ввода из этого диалогового окна передается в переменную kolvo. Если поле ввода пустое или в диалоговом окне была нажата кнопка отмены «Cancel», тогда дальнейшие инструкции не выполняться и работа макроса прерывается.
В следующей строке кода проверяется: является ли введенное значение в поле ввода – числовым? Если да, тогда на всякий случай удаляются все числа после запятой с помощью функции Fix.
Далее в переменой list создается экземпляр объекта ActiveSheet. После в цикле копируются листы. Количество циклов выполняется ровно столько, сколько пользователь указал в диалоговом окне макроса. В процессе копирования каждый раз изменяется название для новой копии листа. Так как в одной книге не может быть 2 и более листов с одинаковым названием. Уникальные названия для каждой копии создаются за счет присвоения к названию исходного листа число с порядковым номером текущего цикла. При необходимости пользователь может задать свои параметры для присвоения названия копиям листов изменив данную строку кода. Главное придерживаться правила уникальности названий листов.
Примечание. Если нет необходимости настраивать названия для новых листов, тогда данную строку кода можно закомментировать.
‘ActiveSheet.Name = list.Name & i
В таком случае названия для копий Excel будет присваивать сам. Например, для исходного листа с названием «Лист1» копии будут получать названия: «Лист1 (2)», «Лист1 (3)», «Лист1 (4)» и т.д.
В конце кода выводиться сообщение на тот случай если пользователь неправильно указал числовое значение в поле ввода диалогового окна макроса.
Источник
Sheets.Copy method (Excel)
Copies the sheet to another location in the workbook.
Syntax
expression.Copy (Before, After)
expression A variable that represents a Sheets object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Before | Optional | Variant | The sheet before which the copied sheet will be placed. You cannot specify Before if you specify After. |
After | Optional | Variant | The sheet after which the copied sheet will be placed. You cannot specify After if you specify Before. |
If you don’t specify either Before or After, Microsoft Excel creates a new workbook that contains the copied sheet.
Example
This example copies Sheet1, placing the copy after Sheet3.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
How to duplicate sheet in Excel with VBA
by Svetlana Cheusheva, updated on March 16, 2023
The tutorial provides a collection of macros to duplicate sheets in Excel: copy and rename based on cell value, copy multiple sheets, copy an active worksheet to another file without opening it, and more.
Manually copying sheets in Excel is pretty quick and straightforward. if performed just once or twice. Duplicating multiple sheets multiple times is boring and time consuming. On this page, you will find a handful of useful macros to automate this task.
Excel VBA to copy sheet to new workbook
This simplest one-line macro does exactly what its name suggests — copies the active sheet to a new workbook.
Copy multiple sheets in Excel with VBA
If you’d like to copy several sheets from the active workbook to a new one, select all the worksheets of interest and run this macro:
Excel VBA to copy sheet to another workbook
Depending on where you want to insert the copied sheet, use one of the following macros.
Copy sheet to the beginning of another workbook
This macro copies the active sheet before all other worksheets in the destination file, Book1 in this example. To copy to another file, replace «Book1.xlsx» with the full name of your target workbook.
Copy sheet to the end of another workbook
This piece of code duplicates the active worksheet and places the copy to the end of Book1. Again, please remember to replace «Book1.xlsx» with the name of your destination workbook.
Note. For the macros to work, the target workbook must be saved on your hard drive or network.
Copy sheet to a selected workbook
To be able to copy the current sheet to any open workbook, you can create a UserForm (named UserForm1) with a ListBox control (named ListBox1) and two buttons:
Next, double-click the form and paste the below code in the Code window:
With the UserForm in place, you can use one of the following macros to copy the active sheet to the workbook of your choosing.
Copy sheet to the beginning of the selected workbook:
Copy sheet to the end of the selected workbook:
When run in Excel, the macro will show you a list of all currently opened workbooks. You select the needed one and click OK:
Excel macro to copy sheet and rename
When you copy a sheet in Excel, the replica is given a name in the default format like Sheet1 (2). The following macros can spare you the trouble of changing the default name manually.
This code duplicates the active worksheet, names the copy as «Test Sheet» (you are free to replace it with any other name you like), and places the copied sheet at the end of the current workbook.
To allow the user to specify the name for the copied sheet, use this code:
Upon running, the macro displays the following input box, in which you type the desired name and press OK:
Excel macro to copy sheet and rename based on cell value
In some situations, it may be more convenient to name a copy with a specific cell value, for example, a column header. For this, you simply take the above code and supply the value of the currently selected cell to the input box automatically. As with the previous example, the copy will be placed at the end of the active workbook.
The trickiest part would be to have your users always select the correct cell before running the macro 🙂
Alternatively, you can hardcode the address of the cell by which the copy should be named, cell A1 in the below code. To name the copied worksheet based on another cell, replace A1 with an appropriate cell reference.
Macro to copy worksheet to a closed workbook
This macro copies the active sheet to the end of a closed workbook. The name of another workbook is not specified in the code — the macro will open the standard Windows Explorer window and allow you to choose any destination file:
After you select the file and click Open, the macro will copy the active sheet and close the target workbook automatically.
Excel VBA to copy sheet from another workbook without opening
This macro enables you to copy a worksheet from another Excel file without opening it. The copied sheet will be inserted at the end of the current workbook.
Just remember to make a couple of replacements in the code:
- C:UsersXXXDocumentsTarget_Book.xlsx should be changed to the actual path and name of the workbook from which you want to copy a sheet.
- Sheet1 should be replaced with the name of the sheet you want to copy.
Excel VBA to duplicate sheet multiple times
Sometimes, you may need to duplicate the same sheet more than once, for instance to test different formulas on the same data set. This can be easily done with the following macro.
Open the original sheet, run the macro, specify how many copies of the active sheet you want to make, and click OK:
How to duplicate sheets in Excel with VBA
To copy a sheet in Excel with one of the above macros, you can either insert the VBA code into your own book or run a macro from our sample workbook.
How to add a macro to your workbook
To insert the code in your workbook, perform these steps:
- Open the worksheet you want to copy.
- Press Alt + F11 to open the Visual Basic Editor.
- On the left pane, right-click ThisWorkbook, and then click Insert >Module.
- Paste the code in the Code window.
- Press F5 to run the macro.
For the detailed step-by-step instructions, please see How to insert VBA code in Excel.
How to run a macro from our sample workbook
Alternatively, you can download our sample workbook to Duplicate Excel Sheets and run the code from there.
The sample workbook contains the following macros:
CopySheetToNewWorkbook — copies the current worksheet to a new workbook.
CopySelectedSheets — copies multiple sheets that you select to a new workbook.
CopySheetToBeginningAnotherWorkbook — copies the active sheet to the beginning of another workbook.
CopySheetToEndAnotherWorkbook — copies the active sheet to the end of another Excel file.
CopySheetAndRename — duplicates the current sheet, renames it as specified by the user, and puts the copy after all other sheets in the current workbook.
CopySheetAndRenamePredefined — duplicates the active sheet, gives a hardcoded name to the copy and places it at the end of the current workbook.
CopySheetAndRenameByCell — makes a copy of the active sheet and renames it based on the selected cell value.
CopySheetAndRenameByCell2 — copies the active sheet and renames it based on the hardcoded cell address.
CopySheetToClosedWorkbook — allows you to copy sheet to a closed workbook.
CopySheetFromClosedWorkbook — enables you to copy a sheet from another Excel file without opening it.
DuplicateSheetMultipleTimes — lets you duplicate a sheet in Excel multiple times.
To run the macro in your Excel, just do the following:
- Open the downloaded workbook and enable the content if prompted.
- Open your own workbook and navigate to the sheet you want to copy.
- In your worksheet, press Alt + F8 , select the macro of interest, and click Run.
That’s how you can duplicate a sheet in Excel with VBA. I thank you for reading and hope to see you on our blog next week!
You may also be interested in
Table of contents
I am running the «Excel macro to copy sheet and rename» where it allows the user to save a new name. However, when I create it, it renames the old version then creates a duplicate of the original and puts in for example test (2). I want to keep the original and have the new named sheet at the end of the workbook. Here is my coding:
Sub CopySheetAndRename()
Dim newName As String
On Error Resume Next
newName = InputBox(«Enter the name for the copied worksheet»)
If newName «» Then
Sheets(«Portfolio Plus»).Copy After:=Worksheets(Sheets.Count)
On Error Resume Next
Sheets(«Portfolio Plus»).Name = newName
End If
End Sub
I have a worksheet where I would like to copy two worksheets and rename them. The two worksheets are named by date. How could I amend the macro to name the two new worksheets with the date+1 of the previous worksheets?
I have a template with named ranges in tables that I use to export data from SAS (One range per sheet, 9 sheets). I keep ending up with corrupted files and I was told to copy everything to a new workbook and try again. However, I get an error «You cannot copy or move a group of sheets that contain tables.»
I am very new to VBA, so any advice is appreciated!
Hi!
Convert your tables to a normal Excel range. VBA macros do not work with tables.
The following tutorial should help: Convert Excel table to range and turn data range into table.
I have set up the COPY A WORKSHEET AND RENAME macro but it copies the new worksheet AFTER (to the right of) the source. I want it to copy before..I tried changing the «After» command to «Before» but this did not work. suggestions?
Quiero copiar la hoja T3 y reemplazar con ella las hojas T1 y T2 sin que se disparen errores de Ref! en la hoja Indice
HI
Is there a way to run a macro to copy all comment thread/notes from cells to a new worksheet?
I’ve tried and found VB code but it didnt seem to work, I’m using office 365.
Thanks
Hello.
I am trying to place a shape button on sheets in a workbook so when data is filled for a week. I like copy this sheet say name of workbook is » working on» and sheet name » weekly report» when this page is filed for the week. I want copy this sheet in to closed work book say name is «weekly reports Archive» and place it at end of all sheets and name the sheet i am copying to «weekly report wk 21» after weekly report 20 sheet. All work books and sheets are shared for updates and want to make it more easier for others to update. Would you be able to help. I am new to VBA coding.
I recived «path not found ‘.vbbad70.tmp’ while i used:
Sheets(SheetCount).Copy After:=Sheets(SheetCount)
Hi thank you very much for these codes, it really saves a lot of time.I have question in regards to the copying of a sheet to a closed workbook.When I tried to do that it gives me a runtime error’91’ «currentSheet.Copy After:=closedBook.Sheets(closedBook.Worksheets.Count)».I’m copying to a hard drive. Will be glad if you can assist. Regards, Jan.
Hi,
It is very useful.
Can you help me with the codes to copy multiple sheets (Only values & format) from workbook to new workbook.
Thanks!
Amazing thank you! Did exactly what I needed it to (with some easy modifications)
Hi,
re Power Pivot / Manage in Data Model
I get this message «PowerPivot is unable to load the Data Model.»
I have tried a lot of ways to sort this problem, but no luck.
Do you think it would work if I export all the modules and Sheets individually and then import them into a new clear Workbook (.xlsm)
Dear Sir,
I have a workbook in which a sheet with some formulas. I want a duplicate copy of this sheet and rename with a cell value. And I want this duplicate sheet with Cell values only (as paste special). I did it with the help of your formulas but it is copy and pasting on the source sheet not on duplicate sheet. Please help me.
Private Sub CommandButton1_Click()
Dim wks As Worksheet
Set wks = ActiveSheet
ActiveSheet.Copy After:=Worksheets(Sheets.Count)
If wks.Range(«b9»).Value «» Then
On Error Resume Next
ActiveSheet.Name = wks.Range(«b9»).Value
End If
CommandButton2_Click
‘wks.Activate
End Sub
Private Sub CommandButton2_Click()
Worksheets(Sheets.Count).Activate
Range(«a1:s36»).Copy
Range(«a1:s36»).PasteSpecial xlPasteValues
End Sub
Morning all,
The above macros are extremely useful, but is there a way to copy the sheet across as «values only», similar to the PasteSpecial method?
Could anyone please help me on how to copy sheets with shapes?
My code is referencing to a specific shape, therefore when I copy the sheet, names of the shapes change.
How can I prevent this?
Is there a way to write a code that doesn’t have to reference each shape?
Thank you for your help.
I am trying to duplicate a excel sheet multiple times, rename them based on an Excel List, and then populate the column next to the sheet name with a link to the sheet.
The list is found in the «Cover» sheet and I want to copy the «Template» sheet based on the list selection. The link shortcut will be in the cover sheet in the column next to the cell that was used to generate the sheet name. There will be a lot of tabs and this will make life a lot easier if there is a link from the cover page
Is this possible, and if so how can I do it?
Hi
Is it possible to overwrite a sheet of the same name in the worksheet where the sheet is to be copied? I need to be able to copy the same sheet from time to time. Please help?
Hi,
Your macros have been extremely helpful.
I really appreciate your work. Thank you.
Thank you so much.
Excel macro to copy sheet and rename
Is there anyway for the button to be on one sheet but instead of copying the active sheet it copies the sheet called New Hire?
Excel VBA to duplicate sheet multiple times:
This is the closest to what I am trying to do. But all the new sheets are named he same as the original but with (x). i.e. Original sheet is 10001 and I need them to number 10002, 10003, etc. But they are numbering 10001, 10001(1), 10001(2).
How can I get my sheet tabs to number the way I want? Any help would be greatly appreciated.
Thanks!
Thanks for this vba «Excel VBA to copy sheet from another workbook without opening» which works excellently in its current form. Can you please tweak it a little so that instead of giving a specific path, a window opens and I select the file from which data needs to be pulled. Rest it should remain the same. Thanks in advance.
Hi I have used your code titled «Excel VBA to duplicate sheet multiple times»
but how shall I rename the sheets? I want them to be in numbers.
Eg
Original Sheet is «master’
Copy need 5
result shall be in sheet name as
Point 1
Point 2
Point 3
Point 4
Point 5
—[Snip, Snip]—
Public Sub DuplicateSheetMultipleTimes()
Dim n As Integer
On Error Resume Next
n = InputBox(«How many copies of the active sheet do you want to make?»)
If n >= 1 Then
For numtimes = 1 To n
activeSheet.Copy After:=ActiveWorkbook.Sheets(Worksheets.Count)
ActiveSheet.name = «Point » + CStr(numtimes)
Next
End If
End Sub
—[Snip, Sni
This will cause the various copied sheets to be renamed as they are copied
Hi,
I have a workbook with many sheets. I need particular cells copied from sheet 1,sheet2 of Workbook1 and show it in another workbook. For example I have the dealer ID and name in Sheet1 and the rating in sheet5 of the same workbook1. I need to pull the rating using ID which is unique to another worksheet and then I need the ID field to be dynamic. How do I do it? please advise.
Is it possible to pick up a range of tabs? For example, the macro requires that I list the tab names individually ie.Sheets(Array («Tab1», «Tab2», «Tab3», “etc…”)).Copy)
What if I want to pick up all the tabs between «Tab1» and «Tab8» without listing them all individually? Is this possible?
Hello, your macros have been extremely helpful.
I was wondering if the following can be achieved
1) I select a range, say A2-A15, which contains the names of worksheets in a particular workbook.
2) I want to create a new workbook with the selected worksheet names from the active workbook using the following formula:
“
Sub Copy_Worksheets()
Worksheets(Array(«ACC_HF», «ACC_Aflac», “etc…”)).Copy
End Sub
”
Is there a way to convert the selected range and pass is to the array argument?
How can i copy data from a range of cells say B5:I39 from multiple worksheets and paste them to one new worksheet, i want to be able to have all selected worksheets with specific data range to be copied to one worksheet at the end of the workbook. All formatting from selected sheets to be coppied across too.
Thanks for the tip, is there a way to copy a row in one workbook and paste that row of data to a different workbook on a specific cell? There is a catch though, the data will need to sync to a different tab of the same workbook every other month.
That’s great
how can I copy sheets containing a specific text string somewhere on the sheet, to a new workbook?
Источник
You can easily copy sheets in Excel manually with a few simple mouse clicks. On the other hand, you need a macro if you want to automate this process. In this guide, we’re going to show you how to copy sheets in Excel with VBA.
Download Workbook
Before you start
If you are new to VBA and macro concept, VBA is a programming language for Office products. Microsoft allows users to automate tasks or modify properties of Office software. A macro, on the other hand, is a set of VBA code which you tell the machine what needs to be done.
Macros, or codes, should be written in modules, which are text areas in VBA’s dedicated user interface. Also, the file should be saved as Excel Macro Enabled Workbook in XLSM format to keep the codes.
You can find detailed instructions in our How to create a macro in Excel guide.
New Workbook
Copy active sheet to a new workbook
The first code is the simplest and shortest one which performs the action the title suggests:
Public Sub CopyActiveSheetToNewWorkbook() ActiveSheet.Copy End Sub
As you can figure out ActiveSheet selector indicates the active sheet in the user window. Once the code run successfully, you will see the copy in a new workbook.
Copy a specific sheet to a new workbook
The following code copies “SUMIFS” sheet into a new workbook, regardless of sheet’s active status.
Public Sub CopySpecificSheetToNewWorkbook() Sheets("SUMIFS").Copy End Sub
Copy selected sheets to a new workbook
If you need to copy selected sheets into a new workbook, use ActiveWindow.SelectedSheets selector.
Public Sub CopyActiveSheetsToNewWorkbook() ActiveWindow.SelectedSheets.Copy End Sub
Copy active sheet to a specific position in the same workbook
If you specify a position in the code, VBA duplicates the sheet in a specific position of in the workbook. To do this placement, you can use Before and After arguments with Copy command. With these arguments, you can place the new sheet before or after an existing worksheet.
You can use either sheet names or their indexes to indicate the existing sheet. Here are a few samples:
Public Sub CopyActiveSheetAfterSheet_Name() 'Copies the active sheet after "Types" sheet ActiveSheet.Copy After:=Sheets("Types") End Sub Public Sub CopyActiveSheetAfterSheet_Index() 'Copies after 2nd sheet ActiveSheet.Copy After:=Sheets(2) End Sub Public Sub CopyActiveSheetAfterLastSheet() 'Copies the active sheet after the last sheet 'Sheets.Count command returns the number of the sheets in the workbook ActiveSheet.Copy After:=Sheets(Sheets.Count) End Sub Public Sub CopyActiveSheetBeforeSheet_Name() 'Copies the active sheet before "Types" sheet ActiveSheet.Copy Before:=Sheets("Types") End Sub Public Sub CopyActiveSheetBeforeSheet_Index() 'Copies the active sheet before 2nd sheet ActiveSheet.Copy Before:=Sheets(2) End Sub Public Sub CopyActiveSheetBeforeFirstSheet() 'Copies the active sheet before the first sheet ActiveSheet.Copy Before:=Sheets(1) End Sub
Copy active sheet to an existing workbook
To copy anything to an existing workbook, there are 2 perquisites:
- Target workbook should be open as well
- You need to specify the target workbooks by name
Sub CopySpecificSheetToExistingWorkbook() ' define a workbook variable and assign target workbook ' thus, we can use variable multiple times instead of workbook reference Dim targetSheet As Workbook Set targetSheet = Workbooks("Target Workbook.xlsx") 'copies "Names" sheet to the last position in the target workbook Sheets("Names").Copy After:=targetSheet.Sheets(targetSheet.Worksheets.Count) End Sub
Note: To copy to a closed workbook is possible. However, the target workbook should be opened and preferably closed after copying via VBA as well.
In this Article
- Copy Worksheet to New Workbook
- Copy ActiveSheet to New Workbook
- Copy Multiple Sheets to New Workbook
- Copy Sheet Within Same Workbook
- Copy Sheet Before Another Sheet
- Copy Sheet Before First Sheet
- Copy Sheet After Last Sheet
- Move Sheet
- Copy and Name Sheet
- Copy and Name Sheet Based on Cell Value
- Copy Worksheet to Another Workbook
- Copy Worksheet to a Closed Workbook
- Copy Sheet from Another Workbook Without Opening it
- Duplicate Excel Sheet Multiple times
This tutorial will cover how to copy a Sheet or Worksheet using VBA.
Copy Worksheet to New Workbook
To copy a Worksheet to a new Workbook:
Sheets("Sheet1").Copy
Copy ActiveSheet to New Workbook
To copy the ActiveSheet to a new Workbook:
ActiveSheet.Copy
Copy Multiple Sheets to New Workbook
To copy multiple Sheets to a new workbook:
ActiveWindow.SelectedSheets.Copy
Copy Sheet Within Same Workbook
We started off by showing you the most simple copy Sheets example: copying Sheet(s) to a new Workbook. These examples below will show you how to copy a Sheet within the same Workbook. When copying a Sheet within a Worbook, you must specify a location. To specify a location, you will tell VBA to move the Worksheet BEFORE or AFTER another Worksheet.
Copy Sheet Before Another Sheet
Here we will specify to copy and paste the Sheet before Sheet2
Sheets("Sheet1").Copy Before:=Sheets("Sheet2")
Copy Sheet Before First Sheet
Instead of specifying the Sheet name, you can also specify the Sheet position. Here we are copying and pasting a Sheet before the first Sheet in the Workbook.
Sheets("Sheet1").Copy Before:=Sheets(1)
The newly created Sheet will now be the first Sheet in the Workbook.
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!
Learn More
Copy Sheet After Last Sheet
Use the After property to tell VBA to paste the Sheet AFTER another sheet. Here we will copy and paste a Sheet after the last Sheet in the Workbook:
Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
Notice that we used Sheets.Count to count the number of Sheets in the Workbook.
Move Sheet
You can also move a Sheet within a Workbook using similar syntax. This code will move Sheet1 to the end of the Workbook:
Sheets("Sheet1").Move After:=Sheets(Sheets.Count)
Copy and Name Sheet
After copying and pasting a Sheet, the newly created sheet becomes the ActiveSheet. So to rename our new sheet, simply use ActiveSheet.Name:
Sub CopySheetRename1()
Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = "LastSheet"
End Sub
If the Sheet name already exists, the above code will generate an error. Instead we can use “On Error Resume Next” to tell VBA to ignore naming the Sheet and proceed with the rest of the procedure:
Sub CopySheetRename2()
Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
On Error Resume Next
ActiveSheet.Name = "LastSheet"
On Error GoTo 0
End Sub
Or use our RangeExists Function to test if the Sheet name already exists before attempting to copy the sheet:
Sub CopySheetRename3()
If RangeExists("LastSheet") Then
MsgBox "Sheet already exists."
Else
Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = "LastSheet"
End If
End Sub
Function RangeExists(WhatSheet As String, Optional ByVal WhatRange As String = "A1") As Boolean
Dim test As Range
On Error Resume Next
Set test = ActiveWorkbook.Sheets(WhatSheet).Range(WhatRange)
RangeExists = Err.Number = 0
On Error GoTo 0
End Function
VBA Programming | Code Generator does work for you!
Copy and Name Sheet Based on Cell Value
You might also want to copy and name a Sheet based on a Cell Value. This code will name the Worksheet based on the Cell value in A1
Sub CopySheetRenameFromCell()
Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
On Error Resume Next
ActiveSheet.Name = Range("A1").Value
On Error GoTo 0
End Sub
Copy Worksheet to Another Workbook
So far we’ve worked with copying Sheets within a Workbook. Now we will cover examples to copy and paste Sheets to other Workbooks. This code will copy a Sheet to the beginning of another workbook:
Sheets("Sheet1").Copy Before:=Workbooks("Example.xlsm").Sheets(1)
This will copy a Worksheet to the end of another Workbook.
Sheets("Sheet1").Copy After:=Workbooks("Example.xlsm").Sheets(Workbooks("Example.xlsm").Sheets.Count)
Notice we replaced 1 with Workbooks(“Example.xlsm”).Sheets.Count to get the last Worksheet.
Copy Worksheet to a Closed Workbook
You might also want to copy a Worksheet to a Workbook that is closed. This code will open a closed Workbook so that you can copy a Sheet into it.
Sub CopySheetToClosedWB()
Application.ScreenUpdating = False
Set closedBook = Workbooks.Open("D:Dropboxexcelarticlesexample.xlsm")
Sheets("Sheet1").Copy Before:=closedBook.Sheets(1)
closedBook.Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub
Copy Sheet from Another Workbook Without Opening it
Conversely, this code will copy a Worksheet FROM a closed Workbook without you needing to manually open the workbook.
Sub CopySheetFromClosedWB()
Application.ScreenUpdating = False
Set closedBook = Workbooks.Open("D:Dropboxexcelarticlesexample.xlsm")
closedBook.Sheets("Sheet1").Copy Before:=ThisWorkbook.Sheets(1)
closedBook.Close SaveChanges:=False
Application.ScreenUpdating = True
End Sub
Notice that in both these examples we disabled ScreenUpdating so the process runs in the background.
Duplicate Excel Sheet Multiple times
You can also duplicate an Excel Sheet multiple times by using a Loop.
Sub CopySheetMultipleTimes()
Dim n As Integer
Dim i As Integer
On Error Resume Next
n = InputBox("How many copies do you want to make?")
If n > 0 Then
For i = 1 To n
ActiveSheet.Copy After:=ActiveWorkbook.Sheets(Worksheets.Count)
Next
End If
End Sub