Создание файлов Excel методами Workbooks.Add, Worksheet.Copy и текстовых файлов с помощью оператора Open и метода CreateTextFile из кода VBA Excel. Создание документов Word рассмотрено в отдельной статье.
Метод Workbooks.Add
Описание
Файлы Excel можно создавать из кода VBA с помощью метода Add объекта Workbooks.
Workbooks.Add – это метод, который создает и возвращает новую книгу Excel. Новая книга после создания становится активной.
Ссылку на новую книгу Excel, созданную методом Workbooks.Add, можно присвоить объектной переменной с помощью оператора Set
или обращаться к ней, как к активной книге: ActiveWorkbook
.
Синтаксис
Workbooks.Add (Template)
Template – параметр, который определяет, как создается новая книга.
Значение Template | Параметры новой книги |
---|---|
Отсутствует | Новая книга с количеством листов по умолчанию. |
Полное имя существующего файла Excel | Новая книга с указанным файлом в качестве шаблона. |
xlWBATChart | Новый файл с одним листом диаграммы. |
xlWBATWorksheet | Новый файл с одним рабочим листом. |
Примеры
Пример 1
Создание новой книги Excel с количеством листов по умолчанию и сохранение ее в папку, где расположен файл с кодом VBA:
Sub Primer1() ‘Создаем новую книгу Workbooks.Add ‘Сохраняем книгу в папку, где расположен файл с кодом ActiveWorkbook.SaveAs (ThisWorkbook.Path & «Моя новая книга.xlsx») ‘Закрываем файл ActiveWorkbook.Close End Sub |
Файл «Моя новая книга.xlsx» понадобится для следующего примера.
Пример 2
Создание новой книги по файлу «Моя новая книга.xlsx» в качестве шаблона с присвоением ссылки на нее объектной переменной, сохранение нового файла с новым именем и добавление в него нового рабочего листа:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Sub Primer2() ‘Объявляем объектную переменную с ранней привязкой Dim MyWorkbook As Workbook ‘Создаем новую книгу по шаблону файла «Моя новая книга.xlsx» Set MyWorkbook = Workbooks.Add(ThisWorkbook.Path & «Моя новая книга.xlsx») With MyWorkbook ‘Смотрим какое имя присвоено новому файлу по умолчанию MsgBox .Name ‘»Моя новая книга1″ ‘Сохраняем книгу с новым именем .SaveAs (ThisWorkbook.Path & «Моя самая новая книга.xlsx») ‘Смотрим новое имя файла MsgBox .Name ‘»Моя самая новая книга» ‘Добавляем в книгу новый лист с именем «Мой новый лист» .Sheets.Add.Name = «Мой новый лист» ‘Сохраняем файл .Save End With End Sub |
Метод Worksheet.Copy
Описание
Если в коде VBA Excel применить метод Worksheet.Copy без указания параметра Before или After, будет создана новая книга с копируемым листом (листами). Новая книга станет активной.
Примеры
Пример 3
Создание новой книги с помощью копирования одного листа (в этом примере используется книга, созданная в первом примере):
Sub Primer3() ‘Если книга источник не открыта, ее нужно открыть Workbooks.Open (ThisWorkbook.Path & «Моя новая книга.xlsx») ‘Создаем новую книгу копированием одного листа Workbooks(«Моя новая книга.xlsx»).Worksheets(«Лист1»).Copy ‘Сохраняем новую книгу с именем «Еще одна книжица.xlsx» в папку, ‘где расположен файл с кодом ActiveWorkbook.SaveAs (ThisWorkbook.Path & «Еще одна книжица.xlsx») End Sub |
Также, как и при создании нового файла Excel методом Workbooks.Add, при создании новой книги методом Worksheet.Copy, можно ссылку на нее присвоить объектной переменной.
Пример 4
Создание новой книги, в которую включены копии всех рабочих листов из файла с кодом VBA:
Sub Primer4() ThisWorkbook.Worksheets.Copy End Sub |
Пример 5
Создание новой книги, в которую включены копии выбранных рабочих листов из файла с кодом VBA:
Sub Primer5() ThisWorkbook.Sheets(Array(«Лист1», «Лист3», «Лист7»)).Copy End Sub |
Создание текстовых файлов
Оператор Open
При попытке открыть несуществующий текстовый файл с помощью оператора Open, такой файл будет создан. Новый файл будет создан при открытии его в любом режиме последовательного доступа, кроме Input (только для чтения).
Пример
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Sub Primer6() Dim ff As Integer, ws As Object ‘Получаем свободный номер для открываемого файла ff = FreeFile ‘Создаем новый текстовый файл путем открытия ‘несуществующего в режиме чтения и записи Open ThisWorkbook.Path & «Мой-новый-файл.txt» For Output As ff ‘Записываем в файл текст Write #ff, «Этот файл создан при его открытии оператором « & _ «Open по несуществующему адресу (полному имени).» ‘Закрываем файл Close ff ‘Открываем файл для просмотра Set ws = CreateObject(«WScript.Shell») ws.Run ThisWorkbook.Path & «Мой-новый-файл.txt» Set ws = Nothing End Sub |
В имени текстового файла пробелы заменены дефисами (знаками минус), так как метод Run объекта Wscript.Shell не способен открывать файлы с именами, содержащими пробелы.
Рекомендую открывать файлы для просмотра методом ThisWorkbook.FollowHyperlink. Пример и преимущества этого метода в статье VBA Excel. Открыть файл другой программы.
Метод FileSystemObject.CreateTextFile
Для создания нового текстового файла из кода VBA Excel по указанному имени, можно использовать метод CreateTextFile объекта FileSystemObject.
Пример
Sub Primer7() Dim fso, fl, ws ‘Создаем новый экземпляр объекта FileSystemObject Set fso = CreateObject(«Scripting.FileSystemObject») ‘Присваиваем переменной fl новый объект TextStream, ‘связанный с созданным и открытым для записи файлом Set fl = fso.CreateTextFile(ThisWorkbook.Path & «Еще-один-текстовый-файл.txt») ‘Записываем в файл текст fl.Write («Этот текстовый файл создан методом CreateTextFile объекта FileSystemObject.») ‘Закрываем файл fl.Close ‘Открываем файл для просмотра Set ws = CreateObject(«WScript.Shell») ws.Run ThisWorkbook.Path & «Еще-один-текстовый-файл.txt» End Sub |
Стоит отметить, что новый текстовый файл может быть создан и с помощью метода OpenTextFile объекта FileSystemObject при условии присвоения параметру create значения True.
One of the most basic and common operations in Excel is creating a new workbook. You’ve probably created a countless number of new workbooks yourself.
If you’re automating some of your Excel work by using Visual Basic for Applications, the ability to create new workbooks can be of immense help. You may want, for example, do any of the following:
- Create a new workbook based on a particular template.
- Create a workbook with a certain amount and type of sheets.
- Create a new workbook and save it under a particular name.
- Copy or move one or several worksheets to a new workbook.
- Copy a range of cells to a new workbook.
If that’s the case, then this Excel VBA Tutorial should help you. In this blog post, I focus on how you can easily create new Excel workbooks with VBA.
In the first section of this Tutorial, I introduce some of the most relevant VBA constructs (with a focus on the Workbooks.Add method) that can help you to quickly craft a macro that creates a new workbook. In the second section, I provide a step-by-step explanation of 16 practical macro code examples that you can easily adjust and start using today.
Use the following Table of Contents to navigate to the section that interests you the most.
This Excel VBA Create New Workbook Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Let’s start by taking a look the VBA constructs that you’ll be using most of the time for purposes of creating new workbooks, the…
Workbooks.Add Method
You use the Workbooks.Add method to create a new Excel workbook.
The newly created workbook becomes the new active workbook. Therefore, the value that Workbooks.Add returns is a Workbook object representing that newly created workbook.
The syntax of Workbooks.Add is as follows:
expression.Add(Template)
For these purposes, the following definitions are applicable:
- expression: The Workbooks collection.
- Template: Optional parameter. It allows you to specify how Excel creates the new workbook.
As a consequence of the above, I simplify the syntax above as follows:
Workbooks.Add(Template)
Let’s take a closer look at the…
Template Parameter Of Workbooks.Add
Template is the only (optional) argument of Workbooks.Add.
You can use this parameter for purposes of specifying certain characteristics of the newly created workbook. More precisely, Template allows you to determine which of the following option Excel applies when creating the workbook:
- Create a new workbook with the default number of blank sheets. This is the default value of Template. Therefore, Excel does this whenever you omit the parameter.
- Create a new workbook with a single sheet of a certain type. As I explain below, you can choose this option by using the xlWBATemplate constants.
- Use a particular file as a template. You determine the template Excel uses by specifying the name of the relevant file.
If you want to create a new workbook based on an Excel template, you can use the Workbooks.Open method and set the Editable parameter to False. I introduce the Workbooks.Open method further below.
As a consequence of the above, whenever you’re using the Workbooks.Add VBA method, you have the following choices regarding how the new workbook is created:
- Omit the Template Parameter: The newly created workbook contains the default number of blank sheets. This number of sheets:
- Is determined by the Application.SheetsInNewWorkbook property. I provide further information about this property further below.
- Appears (and you can modify it from) within the General tab of the Excel Options dialog.
- Specify an existing Excel file as a string: The file you specify is used as a template for the new workbook.
When specifying the template that Excel uses, include the full path of the file.
- Specify an xlWBATemplate constant: The workbook is created with a single sheet of the type you specify. The following are the 4 constants of the xlWBATemplate enumeration:
- xlWBATWorksheet (-4167): Worksheet.
- xlWBATChart (-4109): Chart sheet.
- xlWBATExcel4MacroSheet (3): Version 4 international macro.
- xlWBATExcel4IntlMacroSheet (4): Version 4 macro.
Other Useful VBA Constructs To Create A New Workbook
Workbooks.Open Method
The Workbooks.Open method is the VBA construct you generally use to open workbooks while working with Visual Basic for Applications.
I provide a thorough explanation of Workbooks.Open and its parameters (including Editable) in this VBA tutorial about opening a workbook. Please check out that blog post if you’re interested in learning more about this particular method.
For purposes of this tutorial, it’s enough for you to know how to use the Open method to create a new workbook based on an Excel template.
Therefore, even though Workbooks.Open has 15 different parameters, I only use 2 of them here:
- FileName.
- Editable.
Considering the above, the following is a very basic syntax of the Workbooks.Open method geared to create a new workbook based on a template:
expression.Open FileName:=yourTemplateName, Editable:=False
For these purposes, the following definitions apply:
- expression: Workbooks object.
- FileName:=yourTemplateName: Filename parameter. “yourTemplateName” is the filename of the Excel template you want to use.
- Editable:=False: Editable parameter set to False. When Editable is False, Excel creates a new workbook based on the template you specify with the FileName parameter.
Considering the above, I further simplify the syntax of Workbooks.Open as follows:
Workbooks.Open FileName:=yourTemplateName, Editable:=False
I don’t cover the other 13 parameters of Workbooks.Open in this blog post. However, you may find some of them useful when creating a new workbook based on a template. If you’re interested in reading more about these parameters, please refer to my tutorial about the topic (to which I link to above).
Application.SheetsInNewWorkbook Property
Application.SheetsInNewWorkbook is the VBA property that determines how many sheets newly created workbooks have. It’s the equivalent of the Include this many sheets setting within the General tab of the Excel Options dialog.
The SheetsInNewWorkbook property is read/write. Therefore, you can use it to specify the number of sheets that is inserted in a workbook you create with the Workbooks.Add method. I provide a practical macro code example (sample #5) further below.
The basic syntax of Applications.SheetsInNewWorkbook is as follows:
expression.SheetsInNewWorkbook
“expression” represents the Excel Application object. Therefore, it’s generally possible to simplify the syntax as follows:
Application.SheetsInNewWorkbook
Sheets.Add, Worksheets.Add, Charts.Add, DialogSheets.Add, Excel4MacroSheets.Add And Excel4IntlMacroSheets.Add Methods
The Application.SheetsInNewWorkbook property allows you to modify the number of sheets that Excel inserts in a newly created workbook. However, consider the following:
- SheetsInNewWorkbook is a property of the Excel Application object. Therefore, any setting modifications you make with VBA apply in general to other newly created workbooks.
- The functionality provided by SheetsInNewWorkbook is relatively limited. In fact, you can only specify the number of sheets that the newly created workbook has.
You can usually handle item #1 above by ensuring that your VBA Sub procedures return SheetsInNewWorkbook to the same setting that applied prior to the macro being executed. Macro example #5 below shows an example of how you can do this.
However, there’s a VBA method that you can use as an alternative to Application.SheetsInNewWorkbook:
Add.
More precisely, the following versions of the Add method:
- Sheets.Add.
- Worksheets.Add.
- Charts.Add.
- DialogSheets.Add.
- Excel4MacroSheets.Add.
- Excel4IntlMacroSheets methods.
I explain these methods in the following sections. Let’s start with the…
Sheets.Add Method
The Sheets.Add method allows you to create any of the following sheets:
- Worksheet.
- Chart sheet.
- Dialog sheet.
- Macro sheet.
After the sheet is created, Sheets.Add activates the new sheet.
The basic syntax of the Sheets.Add method is as follows:
expression.Add(Before, After, Count, Type)
The following are the applicable definitions:
- expression: Sheets object.
- Before: Optional argument. The (existing) sheet before which you want to add the newly created sheet.
- After: Optional parameter. The (existing) sheet after which you want the new sheet to be inserted.
- Count: Optional parameter. Allows you to specify the number of sheets that VBA adds.
The default value of Count (applies if you omit the argument) is 1.
- Type: Optional parameter. You use Type to specify the type of sheet that Excel adds. You can either (i) specify the path and name of the template you want to use, or (ii) use the following values from within the xlSheetType enumeration:
- xlWorksheet (-4167): Worksheet.
xlWorksheet is the default value. Therefore, this is the type of sheet that Excel adds if you omit the Type parameter.
- xlDialogSheet (-4116): Dialog sheet.
- xlChart (-4109): Chart sheet.
- xlExcel4MacroSheet (3): Excel version 4 macro sheet.
- xlExcel4IntlMacroSheet (4): Excel version 4 international macro sheet.
- xlWorksheet (-4167): Worksheet.
The default location of the newly created sheet is before the active sheet. Therefore, this applies if you omit both the Before and After parameters above.
Considering the comments above, I simplify the syntax of the Add method as follows:
Sheets.Add(Before, After, Count, Type)
Worksheets.Add, Charts.Add, DialogSheets.Add, Excel4MacroSheets.Add And Excel4IntlMacroSheets.Add Methods
The following methods are, to a certain extent, substantially similar to the Sheets.Add method above.
- Worksheets.Add.
- Charts.Add.
- DialogSheets.Add.
- Excel4MacroSheets.Add.
- Excel4IntlMacroSheets.Add.
The main difference between all of these methods, is the collection they work with. More precisely:
- Sheets.Add works with the Sheets object. This is the collection of all sheets within the relevant workbook.
- Worksheets.Add works with the Worksheets object. That is, the collection of all worksheets within the appropriate workbook.
- Charts.Add makes reference to the Charts collection. This is the collection of all chart sheets.
- DialogSheets.Add works with the collection of dialog sheets.
- Excel4MacroSheets.Add makes reference to the collection of Excel 4.0 macro sheets in the workbook.
- Excel4IntlMacroSheets.Add works with the collection of Excel 4.0 international macro sheets.
The basic syntax of all the methods is substantially the same as the one I describe above for Sheets.Add. In other words, as follows:
- Worksheets.Add:
Worksheets.Add(Before, After, Count, Type)
- Charts.Add:
Charts.Add(Before, After, Count, Type)
- DialogSheets.Add:
DialogSheets.Add(Before, After, Count, Type)
- Excel4MacroSheets.Add:
Excel4MacroSheets.Add(Before, After, Count, Type)
- Excel4IntlMacroSheets.Add:
Excel4IntlMacroSheets.Add(Before, After, Count, Type)
From a broad perspective, most of the parameters of the Add method act in a similar manner regardless of the object you refer to. Therefore, the comments I make above regarding the Before, After and Count arguments of the Sheets.Add method also apply to this section.
When it comes to the Type parameter, there are some differences. Keep in mind, in particular, the following:
- Worksheets.Add: The default value of Type is xlWorksheet. The method fails if you set Type to xlChart or xlDialogSheet.
- Charts.Add: In this case, the default (and only acceptable) value is xlChart. In other words, the method fails with xlWorksheet, xlExcel4MacroSheet, xlExcel4IntlMacroSheet and xlDialogsheet.
- DialogSheets.Add: The default value is xlDialogSheet. This is also the only acceptable value. The method doesn’t work with xlWorksheet, xlChart, xlExcel4MacroSheet or xlExcel4IntlMacroSheet.
- Excel4MacroSheets.Add: Default value is xlExcel4MacroSheet. The method fails if you try to use xlChart.
- Excel4IntlMacroSheets.Add: The default value of Type is xlExcel4IntlMacroSheet. Similar to the Excel4MacroSheets.Add method, it fails with xlChart.
Workbook.SaveAs Method
From a general perspective, the Workbooks.SaveAs method allows you to save a workbook file.
As I explain in this tutorial, you can use the SaveAs method to create a new workbook with a particular filename.
I provide a very detailed explanation about Workbook.SaveAs method in my blog post about saving Excel workbooks with VBA, which you can find in the Archives. Please refer to that post in order to learn more about this method and all the possibilities it provides.
For purposes of this blog post, I use the following simplified syntax of Workbook.SaveAs:
Workbook.SaveAs Filename:=workbookName
For our purposes, “workbookName” is the name of the workbook you’re creating.
The SaveAs method has 12 different parameters. Filename is only one of them. Other useful parameters that you can use when creating a new workbook with VBA include the following:
- FileFormat: The file format of the newly created/saved workbook.
- Password: Protection password of the new workbook.
Please read my blog post about this topic (I link to the Archives above) to learn more about these other arguments.
Copy Method
Further above, I introduce the following versions of the Add method:
- Sheets.Add.
- Worksheets.Add.
- Charts.Add.
- DialogSheets.Add.
- Excel4MacroSheets.Add.
- Excel4IntlMacroSheets.Add.
Those methods are, at their basic level, substantially similar.
The same thing occurs with the Copy method. For purposes of this VBA tutorial, I focus on the Copy method applied to the following objects:
- Sheet (Sheet.Copy) or Sheets collection (Sheets.Copy).
- Worksheet (Worksheet.Copy) or Worksheets collection (Worksheets.Copy).
- Chart (Chart.Copy) or Charts collection (Charts.Copy).
- Dialog Sheet (DialogSheet.Copy) or Dialog Sheets collection (DialogSheets.Copy).
- Excel 4.0 macro sheet (Excel4MacroSheet.Copy) or Excel 4.0 macro sheets collection (Excel4MacroSheets.Copy).
- Excel 4.0 international macro sheet (Excel4IntlMacroSheet.Copy) or Excel 4.0 international macro sheets collection (Excel4IntlMacroSheets.Copy).
I cover all of these in the following sections:
Sheet.Copy And Sheets.Copy Method
The Sheet.Copy and Sheets.Copy methods allow you to copy a sheet or a collection of sheets to another location.
The basic syntax of these methods is as follows:
expression.Copy(Before, After)
The following definitions apply:
- expression: Sheet or Sheets object.
- Before: Optional parameter. The sheet before which you want to copied sheet(s) to be.
- After: Optional argument. The sheet after which you want to copy the sheet(s).
Therefore, I simplify the syntax as follows, depending on whether the macro works with the whole collection (Sheets) or not (Sheet):
Sheet.Copy(Before, After)
Sheets.Copy(Before, After)
Before and After are mutually exclusive arguments. In other words, you can only use one or the other:
- If you specify Before, don’t use After.
- If you specify After, don’t use Before.
You can omit both Before and After. The consequence of doing this is particularly interesting in the context of creating a new workbook (the topic of this post):
Whenever you use the Sheet.Copy or Sheets.Copy methods without arguments, Excel creates a new workbook with the copied sheet(s). In this case, the syntax is as follows:
Sheet.Copy
Sheets.Copy
Worksheet.Copy, Worksheets.Copy, Chart.Copy, Charts.Copy, DialogSheet.Copy, DialogSheets.Copy, Excel4MacroSheet.Copy, Excel4MacroSheets.Copy, Excel4IntlMacroSheet.Copy And Excel4IntlMacroSheets.Copy Methods
Most of the comments I provide above in connection with the Sheet.Copy and Sheets.Copy methods apply to the following methods:
- Worksheet.Copy or Worksheets.Copy.
- Chart.Copy or Charts.Copy.
- DialogSheet.Copy or DialogSheets.Copy.
- Excel4MacroSheet.Copy or Excel4MacroSheets.Copy.
- Excel4IntlMacroSheet.Copy or Excel4intlMacroSheets.Copy.
The basic (simplified) syntax of the methods I cover in this section is as follows:
- Worksheet.Copy:
Worksheet.Copy(Before, After)
- Worksheets.Copy:
Worksheets.Copy(Before, After)
- Chart.Copy:
Chart.Copy(Before, After)
- Charts.Copy:
Charts.Copy(Before, After)
- DialogSheet.Copy:
DialogSheet.Copy(Before, After)
- DialogSheets.Copy:
DialogSheets.Copy(Before, After)
- Excel4MacroSheet.Copy:
Excel4MacroSheet.Copy(Before, After)
- Excel4MacroSheets.Copy:
Excel4MacroSheets.Copy(Before, After)
- Excel4IntlMacroSheet.Copy:
Excel4IntlMacroSheet.Copy (Before, After)
- Excel4IntlMacroSheets.Copy:
Excel4IntlMacroSheets.Copy(Before, After)
Move Method
The Move method is, to a certain extent, similar to the Copy method I describe in the previous section.
When you manually copy or move a sheet, you use the Move or Copy dialog box. This dialog box allows you to specify whether you want to create a copy or not.
If you choose to create a copy, you’re using the equivalent of the Copy method. Otherwise, you’re working with the equivalent of the Move method.
Similar to the Copy method, you can apply the Move to the following objects:
- Sheet (Sheet.Move) or Sheets collection (Sheets.Move).
- Worksheet (Worksheet.Move) or Worksheets collection (Worksheets.Move).
- Chart (Chart.Move) or Charts collection (Charts.Move).
- Dialog Sheet (DialogSheet.Move) or Dialog Sheets collection (DialogSheets.Move).
- Excel 4.0 macro sheet (Excel4MacroSheet.Move) or Excel 4.0 macro sheets collection (Excel4MacroSheets.Move).
- Excel 4.0 international macro sheet (Excel4IntlMacroSheet.Move) or Excel 4.0 international macro sheets collection (Excel4IntlMacroSheets.Move).
I cover all of these methods in the following sections:
Sheet.Move And Sheets.Move Methods
You can use the Sheet.Move or Sheets.Move methods to move sheet(s) to another location.
The basic syntax of Sheet.Move and Sheets.Move is as follows:
expression.Move(Before, After)
The following definitions are applicable:
- expression: Sheet or Sheets object.
- Before: Optional parameter. Sheet before which you want to place the moved sheet(s).
- After: Optional argument. Sheet after which the moved sheet(s) is(are) located.
Considering the above, I simplify the syntax as follows, depending on whether the macro works with the whole Sheets collection (Sheets.Move) or not (Sheet.Move):
Sheet.Move(Before, After)
Sheets.Move(Before, After)
Similar to what occurs with the Copy method (which I describe above), the following comments are applicable:
- Before and After are mutually exclusive. Therefore, choose to use one or the other (not both).
- If you omit both Before and After, Excel creates a new workbook with the moved sheet(s). Therefore, in this case, you can further simplify the syntax as follows:
Sheet.Move
Sheets.Move
When applying the Move method to a whole collection, bear in mind that an Excel workbook generally must keep at least 1 visible sheet. If execution of your macro results in a workbook not having any visible sheets, you usually get a run-time error.
Worksheet.Move, Worksheets.Move, Chart.Move, Charts.Move, DialogSheet.Move, DialogSheets.Move, Excel4MacroSheet.Move, Excel4MacroSheets.Move, Excel4IntlMacroSheet.Move And Excel4IntlMacroSheets.Move Methods
The following methods are substantially similar to Sheet.Move and Sheets.Move (which I describe above). Therefore, my general comments above are also applicable.
- Worksheet.Move and Worksheets.Move.
- Chart.Move and Charts.Move.
- DialogSheet.Move and DialogSheets.Move.
- Excel4MacroSheet.Move and Excel4MacroSheets.Move.
- Excel4IntlMacroSheet.Move and Excel4IntlMacroSheets.Move.
The basic (simplified) syntax of each of these methods is as follows:
- Worksheet.Move:
Worksheet.Move(Before, After)
- Worksheets.Move:
Worksheets.Move(Before, After)
- Chart.Move:
Chart.Move(Before, After)
- Charts.Move:
Charts.Move(Before, After)
- DialogSheet.Move:
DialogSheet.Move(Before, After)
- DialogSheets.Move:
DialogSheets.Move(Before, After)
- Excel4MacroSheet.Move:
Excel4MacroSheet.Move(Before, After)
- Excel4MacroSheets.Move:
Excel4MacroSheets.Move(Before, After)
- Excel4IntlMacroSheet.Move:
Excel4IntlMacroSheet.Move(Before, After)
- Excel4IntlMacroSheets.Move:
ExcelIntlMacroSheets.Move(Before, After)
Array Function
From a broad perspective, you can define an array by the following characteristics:
- An array is a group of elements.
- The elements have the same name and type.
- The elements are sequentially indexed. Therefore, each element has a unique identifying index number.
I cover the topic of VBA arrays in detail here. Please refer to that tutorial in order to learn more about arrays and how they can help you when working with Visual Basic for Applications.
In the context of this tutorial, arrays help us manipulate several worksheets at once. More precisely, as I show in examples #10 and #13 below, you can use an array to copy or move several worksheets to a new workbook.
The examples below work with the Array Function. Array allows you to obtain a Variant that contains an array. Its basic syntax is as follows:
Array(argumentList)
For these purposes, “argumentList” represents the list of values you want to assign to the array elements. You separate the different arguments using a comma (,).
VBA Constructs To Copy And Paste Ranges
I cover the topic of copying and pasting ranges in this VBA tutorial. Some of the VBA constructs that I explain there are the following:
- The Range.Copy method.
- The Range.PasteSpecial method.
- The Worksheet.Paste method.
- The Range.CopyPicture method.
- The Range.Value property.
- The Range.Formula property.
Explaining each of these constructs exceeds the scope of this VBA tutorial. However, in macro examples #15 and #16 below, I provide VBA code examples that use the Range.Copy method to copy a range to a newly created workbook.
You can use the information and examples I provide in the blog post about copying and pasting with VBA (follow the link I provide above) for purposes of easily using the other VBA constructs I mention above.
The following sections provide you with 16 different practical macro examples that you can adjust and use to create a new workbook. All of the macro code samples below rely, mostly, on the VBA constructs I introduce and describe in the first part of this tutorial above.
Macro Example #1: Excel VBA Create New Workbook With Default Number Of Sheets
If you want to create an Excel workbook that has the default number of worksheets, you can use the following VBA statement:
Workbooks.Add
The following macro example (Create_New_Workbook) shows how you can easily implement this statement:
This macro has the following single statement:
Workbooks.Add
This simply makes reference to the Workbooks.Add method. It uses this method for purposes of adding a new workbook to the Workbooks collection. In other words, the statement simply creates a new workbook.
Even though each of the other macro examples (below) targets a different situation, several of them rely on this basic statement (or a close derivative).
When I execute the sample macro above, Excel simply creates a new workbook with (i) the default name (Book1 in this case), and (ii) the default number of blank worksheets (1 in this example).
Macro Examples #2 And #3: Excel VBA Create New Workbook Using Template
The following statement structure allows you to create a new Excel workbook using an existing file as a template:
Workbooks.Add Template:=”Filename”
For these purposes, “Filename” is the name of the Excel file you’re using as template for the new workbook.
The following macro example (Create_New_Workbook_With_Template_1) uses the Workbooks.Add method and the Template parameter. For purposes of this example, I use this 2016 Olympics Dashboard created by Excel Template authority Dinesh Natarajan Mohan from indzara.com.
The result I obtain when executing this macro is a new Excel workbook that uses Dinesh’s beautiful dashboard as a template.
As an alternative to the above, you can create a new workbook based on an Excel template by working with the Workbooks.Open method. The following basic syntax allows you to do this:
Workbooks.Open Filename:=”TemplateFilename”, Editable:=False
Within this structure, “TemplateFilename” makes reference to the template you want to use.
The following sample macro (Create_New_Workbook_With_Template_2) shows how you can easily implement this structure. For this example, I use this Excel Inventory Management Template (a macro-enabled file) created by Excel expert Puneet Gogia at ExcelChamps.com
When I execute this Sub procedure, Excel creates a new workbook using Puneet’s useful template:
Macro Example #4: Excel VBA Create New Workbook With A Chart Sheet
New Excel workbooks usually come with worksheets. However, if you want to create a new workbook with a chart sheet, use the following VBA statement:
Workbooks.Add Template:=xlWBATChart
The following procedure example (Create_New_Workbook_With_Chart_Sheet) implements this statement:
If I execute this particular macro, Excel creates a new workbook with a single chart sheet:
Macro Examples #5 And #6: Excel VBA Create New Workbook With Several Worksheets
The number of worksheets that Excel includes in a newly created workbook is determined by the Application.SheetsInNewWorkbook property. The following code structure allows you to use this property to create a new workbook that has a different number of worksheets:
Application.SheetsInNewWorkbook = new#
Workbooks.Add
For these purposes, “new#” is the number of worksheets you want the newly created workbook to have.
The process followed by this macro to create the new workbook is as follows:
- Modify the number of worksheets that newly created workbooks have.
- Create a new workbook.
This structure I provide is quite basic. Therefore, it simply modifies the setting that determines how many worksheets are included in a new workbook.
The following sample macro (Create_New_Workbook_Several_Worksheets_1) relies on the structure above to create a new workbook with 3 worksheets. However, it goes one step further and, after creating the workbook, resets the Application.SheetsInNewWorkbook property to its default value.
The process followed by this sample macro to create a new workbook is as follows:
- Reads the current setting of the Application.SheetsInNewWorkbook property (Application.SheetsInNewWorkbook).
- Stores the setting obtained in step #1 within a variable (currentSheetsSetting = ).
- Sets the Application.SheetsInNewWorkbook property to 3 (Application.SheetsInNewWorkbook = 3). Therefore, newly created workbooks have 3 sheets.
- Creates a new workbook (Workbooks.Add).
- Restores the original setting of Application.SheetsInNewWorkbook (Application.SheetsInNewWorkbook = currentSheetsSetting).
The following image illustrates this process:
The following screenshot shows the workbook that Excel creates when I execute this macro sample. Notice that, as expected, it has 3 sheets.
An alternative to relying on the Application.SheetsInNewWorkbook property is to work with the Sheets.Add, Worksheets.Add, Charts.Add or DialogSheets.Add methods that I explain above. These methods have some advantages (including more flexibility) over relying on the Application.SheetsInNewWorkbook property.
In this case, the basic code syntax you can use to create a new workbook with several sheets is as follows:
Workbooks.Add
Worksheets.Add Count:=#
For these purposes, “#” is the number of additional sheets you want to add. The workbook created by Workbooks.Add comes (already) with the number of worksheets determined by the Application.SheetsInNewWorkbook property (usually 1).
This macro follows a relatively simple 2-step process:
- Creates a new workbook.
- Adds a certain number of worksheets (#) to the newly created workbook.
The particular macro structure above works with the Worksheets.Add method. You can, however, also work with the Sheets.Add, Charts.Add or DialogSheets.Add methods by using a similar syntax. For purposes of understanding the differences between each of these methods (and how to use them), please refer to the appropriate section above.
The following macro example (Create_New_Workbook_Several_Worksheets_2) uses the structure above to create a new workbook and (immediately add 2 additional worksheets. The result is a newly created workbook with 3 worksheets.
The following image shows the workbook that Excel creates when I execute this macro. Notice that, just as in the previous example, the newly created workbook has 3 worksheets.
As I mention above, you can use similar macros to work with the Sheets.Add, Charts.Add or DialogSheets.Add methods. The following macro sample provides more ideas of what you can achieve with these methods:
Macro Example #7: Excel VBA Create New Workbook With A Worksheet And A Chart Sheet
If you create a workbook using the Workbooks.Add method, Excel includes the number of sheets determined by the Application.SheetsInNewWorkbook property. You can, however, easily create a workbook that has both a worksheet and a chart sheet using the following basic syntax:
Workbooks.Add
Charts.Add
This macro follows a simple 2-step process to create a new workbook with a worksheet and a chart sheet:
- Creates a new workbook.
- Adds a new chart sheet to the newly created workbook.
The following VBA code example (Create_New_Workbook_Worksheet_Chart_Sheet) implements the structure above without making any changes:
The newly created workbook looks as follows. Notice that, as expected, the workbook has 1 worksheets and 1 chart sheet.
Macro Example #8: Excel VBA Create New Workbook With Name
The Workbooks.Add method by itself creates a new workbook. Generally, the name of the newly created workbook is automatically determined by Excel. The actual name varies slightly depending on how you create the new workbook. However, as a general rule, the filename follows the following structure:
Item#
Usually, “Item” is “Book”. In other words, the newly created workbooks are named Book1, Book2, Book3, etc. However, there are some exceptions to this general rule. For example, if you use the Template parameter of the Workbooks.Add method, the default name of the new workbook is determined on the basis of Template’s value as follows:
- If Template is xlWBATWorksheet: “Item” is “Sheet”. Therefore, workbooks are named Sheet1, Sheet2, Sheet3, etc.
- If Template is xlWBATChart: “Item” is replaced by “Chart”. New workbooks have names such as Chart1, Chart2, Chart3, etc.
- If Template is xlWBATExcel4MacroSheet or xlWBATExcel4IntlMacroSheet: “Item” is “Macro”. The names of new workbooks are Macro1, Macro2, Macro3, and so on.
- If Template specifies an Excel file: “Item” is replaced by the name of the Excel file you specify. As a consequence, new workbooks have the name of Template followed by the appropriate number (TemplateName1, TemplateName2, TemplateName3, and so on).
Excel applies this same rule if you create a new workbook by using the Workbooks.Open method with an Excel template. I show a practical example of a macro that does this in sample #3 above.
Despite the above, you can easily assign a name to the newly created workbook by saving it. Use the following code syntax to do this:
Workbooks.Add.SaveAs Filename:=workbookName
“workbookName” is the name you want to assign to the newly created workbook.
The process followed by this statement to create a new workbook with name is as follows:
- Create a new workbook (Workbooks.Add).
- Save the workbook using the appropriate name (.SaveAs Filename:=workbookName).
The following macro example (Create_New_Workbook_With_Name) uses the structure above to create a new workbook named “Excel VBA Create New Workbook With Name”.
The following screenshot shows the results I get when executing this macro. Notice that, as expected, the workbook is indeed named “Excel VBA Create New Workbook With Name”.
Macro Examples #9, #10 And #11: Excel VBA Copy One Or Several Worksheets To New Workbook
The Copy method allows you to copy sheets to a new workbook. In this section, I show how you can use this method copy one or several worksheets to a new workbook.
In the examples below, I work with the Worksheet.Copy method. You can, however, easily adjust the code in order to work with any of the following:
- Sheet.Copy or Sheets.Copy.
- Chart.Copy or Charts.Copy.
- DialogSheet.Copy or DialogSheets.Copy.
- Excel4MacroSheet.Copy or Excel4MacroSheet.Copy.
- Excel4IntlMacroSheet.Copy or Excel4IntlMacroSheets.Copy.
I explain these methods above.
The following VBA statement allows you to copy a worksheet to a new workbook. In this case, the copied worksheet is the only worksheet in the newly created workbook:
Worksheet.Copy
The following macro example (Copy_Sheet_To_New_Workbook) uses the statement form above in order to copy a worksheet (Copy1) to a new workbook.
The following image shows the results I obtain when running the macro. Notice that the newly created workbook, indeed, contains the copied worksheet (Copy1).
If you want to copy several worksheets to a new workbook, the basic statement structure I explain above continues to apply. In order to get several worksheets at once, you can use the Array Function. The following statement structure can serve you as guidance:
Worksheets(Array(Worksheet1, Worksheet2, …, Worksheet#)).Copy
For these purposes, “Worksheet1” through “Worksheet#” are the worksheets you want to copy.
The following macro example (Copy_Several_Sheets_To_New_Workbook) uses the structure above to copy 5 worksheets (Copy1 through Copy5):
The following screenshot shows the workbook Excel creates when I execute this macro. Notice that, as expected, the worksheets I specified in the macro above (Copy1 through Copy5) are included in the new workbook.
Finally, if your purpose is to copy all of the worksheets within a particular workbook, you can apply the Copy method to the Worksheets collection. The following statement allows you to do this:
Worksheets.Copy
In this case, the newly created workbook contains all the worksheets within the applicable workbook.
The following macro example (Copy_All_Sheets_To_New_Workbook) implements the statement above.
The following image shows the workbook Excel creates when I execute this macro. The newly created workbook contains copies of all the worksheets within the relevant workbook (Copy1 to Copy5, Move1 to Move5 and Range).
Macro Examples #12, #13 And #14: Excel VBA Move One Or Several Worksheets To New Workbook
You can use the logic behind the macros examples that copy worksheets to a new workbook for purposes of moving worksheets to a new workbook. For these purposes, you use the Move method.
Similar to the previous examples #9 to #11, the following sample procedures work with worksheets. However, using the information I provide in the relevant sections above, you can easily adjust them to work with the following methods:
- Sheet.Move or Sheets.Move.
- Chart.Move or Charts.Move.
- DialogSheet.Move or DialogSheets.Move.
- Excel4MacroSheet.Move or Excel4MacroSheet.Move.
- Excel4IntlMacroSheet.Move or Excel4IntlMacroSheets.Move.
Let’s start:
Use the following statement syntax to move a worksheet to a new workbook. The moved worksheet is the only within the newly created workbook.
Worksheet.Move
The following sample VBA code (Move_Sheet_To_New_Workbook) uses the statement structure above to move a worksheet (Move1) to a new workbook:
The following screenshot shows the newly created workbook. Notice that the workbook contains the moved worksheet (Move1).
If you want to move several worksheets to a new workbook use the Array Function alongside the Move method. The basic structure of the relevant statement is as follows:
Worksheets(Array(Worksheet1, Worksheet2, …, Worksheet#)).Move
The following macro example (Move_Several_Sheets_To_New_Workbook) uses this statement to move several worksheets (Move1 through Move5) to a newly created workbook:
The workbook that Excel creates when I execute this macro looks as follows. Notice that the workbook contains the 5 worksheets (Move1 to Move5) that I specified in the code above.
Finally, if you’re moving all of the worksheets within a particular workbook, use Worksheets.Move method. In other words, simply use the following VBA statement:
Worksheets.Move
The following sample macro (Move_All_Worksheets_To_New_Workbook) implements this statement to move all worksheets to a new workbook:
The following image shows the results I get when executing this macro. All worksheets in the applicable workbook (Copy1 to Copy5, Move1 to Move5 and Range) are moved to a new workbook.
The only remaining sheet in the source workbook is an empty chart sheet.
The existence of this chart sheet in the source workbook allows the workbook to comply with the requirement of having at least 1 visible sheet after all worksheets are moved to a new workbook. If this chart sheet doesn’t exist, execution of the Move_All_Worksheets_To_New_Workbook causes a run-time error.
Macro Examples #15 And #16: Excel VBA Copy Range To New Workbook
As I explain above, there are several ways in which you can copy and paste ranges using VBA. In this section, I provide a code example that relies on the Range.Copy method to copy a range to a newly created workbook. Please refer to the relevant section above for purposes of reading about the other VBA constructs you can use for these purposes.
You can use the following statement syntax for purposes of copying a range to the first (usually single) worksheet of a newly created workbook:
Workbook.Worksheet.SourceRange.Copy Destination:=Workbooks.Add.Worksheets(1).DestinationRange
For these purposes, the following definitions apply:
- Workbook.Worksheet.SourceRange: Fully-qualified reference to the range you want to copy.
- DestinationRange: Range where you want Excel to paste the range.
The following macro example (Copy_Range_To_New_Workbook_1) does the following:
- Copies cells B5 to C20 of the worksheet named “Range”. This cells simply contain some randomly generated numbers.
- Pastes the cells it copied in step #1 above in cells B5 to C20 of the first worksheet of a newly created workbook.
The following image shows the results I get when running this macro. The range is copied to cells B5 to C20 of the newly created workbook.
The structure I use in the macro example above, however, may not work properly with a few of the VBA constructs that you can use to copy ranges. A more flexible alternative involves assigning the newly created workbook to an object variable. After this has occurred, you can simply refer to the object variable.
The following basic syntax shows how you can (i) create a new workbook, (ii) assign it to an object variable, and (iii) copy a range to that new workbook.
Dim myNewWorkbook As Workbook
Set myNewWorkbook = Workbooks.Add
Workbook.Worksheet.SourceRange.Copy Destination:=myNewWorkbook.Worksheets(1).DestinationRange
The following macro code example (Copy_Range_To_New_Workbook_2) uses this structure to achieve the same purpose as the previous example above. In other words, this macro does the following:
- Copies cells B5 to C20 of the worksheet named “Range”.
- Pastes those copied cells in cells B5 to C20 of the first worksheet of a newly created workbook.
The following screenshot shows the results I obtain when executing the macro. Notice that they’re substantially the same as those obtained with the previous macro example #15.
Conclusion
Creating a new Excel workbook is one of the most essential and common activities in Excel. Knowing how to use Visual Basic for Applications for purposes of creating new workbooks allows you to automate several processes and become an even more efficient Excel user.
After reading this Excel VBA Tutorial, you have enough knowledge to start or continue developing a wide array of VBA applications that create new Excel workbooks.
In the first section of this blog post, you read about several VBA constructs that are commonly used when creating new workbooks. In that section, you focused on the Workbooks.Add method. This is the most basic and commonly used construct used within macros that create new workbooks.
In that first section, you also read about other VBA constructs that you can use to either (i) add functionality and flexibility to the procedures that create new workbooks or, (ii) create new workbooks without specifically using the Workbooks.Add method.
In the second section of this tutorial, you saw 16 different practical macro examples that you can easily adjust and start using to create new workbooks. Those examples of VBA code cover and target a wide variety of situations. The following are some of the things that these macro examples enable you to do:
- Create a new workbook.
- Use a template to create a new workbook.
- Create workbooks with different types of sheets.
- Create workbooks with a different number of sheets.
- Create a new workbook with a particular name.
- Create or move sheets to a new workbook.
- Copy a range of cells to a new workbook.
Home / VBA / VBA Create New Workbook (Excel File)
To create a new workbook using VBA, you need to use the “Workbooks.Add” method. When you use this method, it inserts a new workbook (without saving it) and activates it after that. It works like when you press the keyboard shortcut CONTROL + N. You can also use a template to insert a new workbook.
Make sure to add the developer tab to the ribbon to enter this code into the VBE.
- Type the keyword “Workbooks” to refer to the workbook object.
- After that, type a dot.
- Here you’ll have a list of properties and methods to select.
- Select “Add” from that list or type it.
Sub vba_new_workbook()
Workbooks.Add
End Sub
Add a New Workbook using a Template
As I said, we are using the Workbooks.Add method. With this method, there’s an argument (optional) that you can use to refer to a file as a template.
Workbook.Add Template (Optional)
Let’s say you have a workbook and want to have the new workbook exactly the same as it, you can refer to it as a template.
Workbooks.Add Template:="C:UsersDellDesktopbook1.xlsx"
When you run the above code, it takes the reference from the “book1” which is saved on the desktop. The template workbook has 6 worksheets and the new workbook has exactly the same number of worksheets.
Apart from this, you can use the default arguments to decide what type of sheet you want to have in the new workbook.
- xlWBATChart: Chart Sheet
- xlWBATExcel4IntlMacroSheet: Macro Sheet Version 4
- xlWBATExcel4MacroSheet: Macro Sheet (International) Version 4
- xlWBATWorksheet: Worksheet
Create a New Excel Workbook and Save it
When you create a new workbook, Excel opens it but will not save it with the Add method. So for this, you need to use the SaveAs method.
Sub vba_create_workbook()
Workbooks.Add
ActiveWorkbook.SaveAs "C:usersdelldesktopmyBook.xlsx"
End Sub
- First, use the workbook.add to create a new workbook.
- Next, refer to the active workbook and use the SaveAs method.
- In the SaveAs method, use the path where you want to save the workbook along with the name of the file.
- In the end, run the code.
More on VBA Workbooks
VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder
- VBA Workbook
Return to VBA Code Examples
In this Article
- Create New Workbook
- Create New Workbook & Assign to Object
- Create New Workbook & Save
- Create New Workbook & Add Sheets
This tutorial will demonstrate different methods to create a new workbook using VBA.
Create New Workbook
To create a new workbook simply use Workbooks.Add:
Workbooks.Add
The newly added Workbook is now the ActiveWorkbook.
You can see this using this code:
Sub AddWB()
Workbooks.Add
MsgBox ActiveWorkbook.Name
End Sub
Create New Workbook & Assign to Object
You can use the ActiveWorkbook object to refer to the new Workbook. Using this, you can assign the new Workbook to an Object Variable:
Dim wb as Workbook
Workbooks.Add
Set wb = ActiveWorkbook
But, it’s better / easier to assign the Workbook immediately to a variable when the Workbook is created:
Dim wb As Workbook
Set wb = Workbooks.Add
Now you can reference the new Workbook by it’s variable name.
MsgBox wb.Name
Create New Workbook & Save
You can also create a new Workbook and immediately save it:
Workbooks.Add.SaveAs Filename:="NewWB"
This will save the Workbook as an .xlsx file to your default folder (ex. My Documents). Instead, you can customize the SaveAs with our guide to saving Workbooks.
Now you can refer to the Workbook by it’s name:
Workbooks("NewWB.xlsx").Activate
This code will Activate “NewWB.xlsx”.
Create New Workbook & Add Sheets
After creating a Workbook you can edit it. Here is just one example to add two sheets to the new Workbook (assuming it’s the ActiveWorkbook):
ActiveWorkbook.Worksheets.Add Count:=2
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!
Create a New Workbook with VBA
Quick trick with Outlook, Word,Excel VBA create new workbook while run-time on the go.
Note: To create a Excel file from Outlook or Word VBA, include reference “Microsoft Excel Object Library’ from VB Editor Menu Tools->References
Once the above reference is made, then the below code will do the rest.
Excel VBA Create New Workbook with Name
From Outlook, Excel or Word follow these steps.
- Press Alt+F11 to open VB Editor.
- Copy paste the below code.
- Ensure file with same name does not exists in path.
- Press F5 to create new Excel workbook.
Private Sub VBA_Create_New_Workbook() 'Add Reference to Microsoft Excel Object Library before this code 'Create New Workbook Workbooks.Add 'Save newly created workbook ActiveWorkbook.SaveAs "D:New_Workbook_From_VBA.xlsx" 'Workbook Close vba ActiveWorkbook.Close End Sub
If the workbook is not closed, then It will be left opened by VBA. So, if you try to open the newly created workbook, then system will notify that workbook is already opened.
Also, if the above code is execute from with in Excel VB Editor, then reference to ‘Microsoft Excel Object Library’ is not required.
VBA to Create New Workbook With Object Reference
Above code just creates a Excel file & save it to a location. If the created workbook has to be referenced with the code, then use the below code.
Private Sub Create_New_Workbook_with_Object() 'Add Reference to Microsoft Excel Object Library before this code Dim objNewExcel As Workbook 'Create New Workbook with Object Set objNewExcel = Workbooks.Add 'VBA Create New Workbook and Copy Data objNewExcel.Sheets(1).Cells(1, 1) = "Copy To New Workbook" 'Save newly created workbook using Object objNewExcel.SaveAs "D:New_Workbook_From_VBA_Obj.xlsx" 'Workbook Close VBA objNewExcel.Save objNewExcel.Close End Sub
This code will assign the newly created workbook to a object. So, this object can be used to write, copy or read content to & from the newly created Excel file.
Refer this page from Microsoft for a more info.
This ends this tutorial. With this tutorial we learned (1). How to Create New Workbook from VBA (2). How to Save newly created Workbook (3). How to copy data to new Excel file using VBA Code.
Always remember to use workbook close vba code, before exiting from any of these macro code.