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!
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
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.
This page explains Excel VBA Workbooks.Add Method, illustrate how to create new workbook in Excel VBA or move data from one workbook to a new workbook
What does Excel VBA Workbooks.Add Method do?
Excel VBA Workbooks.Add Method is used to create new workbook. Suppose you have a workbook called workbook1, inside workbook1 you need to create new workbook and manipulate it, then you need to insert the Workbooks.Add Method in workbook1. After you have created the workbook, the workbook becomes activated, you can set a workbook title, save file, etc.
One common use of Workbooks.Add Method to copy data from a workbook to new worksheets in order to distribute different worksheets to different people.
Syntax of Workbooks.Add Method
Workbooks.Add(Template as Object)
Template | Optional Object. Determines how the new workbook is created. If this argument is a string specifying the name of an existing Microsoft Excel file, the new workbook is created with the specified file as a template. If this argument is a constant, the new workbook contains a single sheet of the specified type.Can be one of the following XlWBATemplate constants: xlWBATChart, xlWBATExcel4IntlMacroSheet, xlWBATExcel4MacroSheet, or xlWBATWorksheet.
If this argument is omitted, Microsoft Excel creates a new workbook with a number of blank sheets (the number of sheets is set by the SheetsInNewWorkbook property). If the Template argument specifies a file, the file name can include a path. |
Remarks
Workbooks.Add is a Method (a Function of an Object), it returns a Workbook Object. You can visually see a workbook opened after using the Method, and you can also define a workbook Object to get the returned Workbook.
Set NewBook = Workbooks.Add
Example 1 – Create new workbook and close it
The below code create a workbook called “New workbook”, and then set the Title and Subject for the workbook, finally save the workbook and close it. As soon as the newly created workbook is closed, the original workbook becomes activated again.
Public Sub createWB() Set newbook = Workbooks.Add With newbook .Title = "This title is displayed in Info > Properties" .Subject = "This subject is displayed in Info > Properties" .SaveAs Filename:="C:UsersWYMANDesktopNew workbook.xlsx" .Close End With End Sub
Example 2 – Move specific data to new workbook
This was a question originally asked in Microsoft Community and answered by me.
Question
I’m sure my issue is not unique. I have a excel document with hundreds of columns and only want about a dozen of them. I need to be able to extract specific
columns to a new excel sheet as a repeated process without manual intervention.
All I need is to pull certain columns into a new excel sheet from an excel document that is updated daily.
Do we have an automated process where I can just run a macro and pull the updated data from an excel document into a new one?
Any help is greatly appreciated.
Thank you.
Answer
The below code extracts specific columns in a workbook and then copy to a new workbook.
Public Sub extractCol() Set range1 = Range("A:D, BI:BI, BQ:BQ,CL:CL,CM:CN,CT:CT,DB:DB") range1.Copy Set newbook = Workbooks.Add ActiveCell.PasteSpecial Paste:=xlPasteValues End Sub
Outbound References
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbooks.add.aspx
In this tutorial, I will cover the how to work with workbooks in Excel using VBA.
In Excel, a ‘Workbook’ is an object that is a part of the ‘Workbooks’ collection. Within a workbook, you have different objects such as worksheets, chart sheets, cells and ranges, chart objects, shapes, etc.
With VBA, you can do a lot of stuff with a workbook object – such as open a specific workbook, save and close workbooks, create new workbooks, change the workbook properties, etc.
So let’s get started.
If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.
Referencing a Workbook using VBA
There are different ways to refer to a Workbook object in VBA.
The method you choose would depend on what you want to get done.
In this section, I will cover the different ways to refer to a workbook along with some example codes.
Using Workbook Names
If you have the exact name of the workbook that you want to refer to, you can use the name in the code.
Let’s begin with a simple example.
If you have two workbooks open, and you want to activate the workbook with the name – Examples.xlsx, you can use the below code:
Sub ActivateWorkbook() Workbooks("Examples.xlsx").Activate End Sub
Note that you need to use the file name along with the extension if the file has been saved. If it hasn’t been saved, then you can use the name without the file extension.
If you’re not sure what name to use, take help from the Project Explorer.
If you want to activate a workbook and select a specific cell in a worksheet in that workbook, you need to give the entire address of the cell (including the Workbook and the Worksheet name).
Sub ActivateWorkbook() Workbooks("Examples.xlsx").Worksheets("Sheet1").Activate Range("A1").Select End Sub
The above code first activates Sheet1 in the Examples.xlsx workbook and then selects cell A1 in the sheet.
You will often see a code where a reference to a worksheet or a cell/range is made without referring to the workbook. This happens when you’re referring to the worksheet/ranges in the same workbook that has the code in it and is also the active workbook. However, in some cases, you do need to specify the workbook to make sure the code works (more on this in the ThisWorkbook section).
Using Index Numbers
You can also refer to the workbooks based on their index number.
For example, if you have three workbooks open, the following code would show you the names of the three workbooks in a message box (one at a time).
Sub WorkbookName() MsgBox Workbooks(1).Name MsgBox Workbooks(2).Name MsgBox Workbooks(3).Name End Sub
The above code uses MsgBox – which is a function that shows a message box with the specified text/value (which is the workbook name in this case).
One of the troubles I often have with using index numbers with Workbooks is that you never know which one is the first workbook and which one is the second and so on. To be sure, you would have to run the code as shown above or something similar to loop through the open workbooks and know their index number.
Excel treats the workbook opened first to have the index number as 1, and the next one as 2 and so on.
Despite this drawback, using index numbers can come in handy.
For example, if you want to loop through all the open workbooks and save all, you can use the index numbers.
In this case, since you want this to happen to all the workbooks, you’re not concerned about their individual index numbers.
The below code would loop through all the open workbooks and close all except the workbook that has this VBA code.
Sub CloseWorkbooks() Dim WbCount As Integer WbCount = Workbooks.Count For i = WbCount To 1 Step -1 If Workbooks(i).Name <> ThisWorkbook.Name Then Workbooks(i).Close End If Next i End Sub
The above code counts the number of open workbooks and then goes through all the workbooks using the For Each loop.
It uses the IF condition to check if the name of the workbook is the same as that of the workbook where the code is being run.
If it’s not a match, it closes the workbook and moves to the next one.
Note that we have run the loop from WbCount to 1 with a Step of -1. This is done as with each loop, the number of open workbooks is decreasing.
ThisWorkbook is covered in detail in the later section.
Also read: How to Open Excel Files Using VBA (Examples)
Using ActiveWorkbook
ActiveWorkbook, as the name suggests, refers to the workbook that is active.
The below code would show you the name of the active workbook.
Sub ActiveWorkbookName() MsgBox ActiveWorkbook.Name End Sub
When you use VBA to activate another workbook, the ActiveWorkbook part in the VBA after that would start referring to the activated workbook.
Here is an example of this.
If you have a workbook active and you insert the following code into it and run it, it would first show the name of the workbook that has the code and then the name of Examples.xlsx (which gets activated by the code).
Sub ActiveWorkbookName() MsgBox ActiveWorkbook.Name Workbooks("Examples.xlsx").Activate MsgBox ActiveWorkbook.Name End Sub
Note that when you create a new workbook using VBA, that newly created workbook automatically becomes the active workbook.
Using ThisWorkbook
ThisWorkbook refers to the workbook where the code is being executed.
Every workbook would have a ThisWorkbook object as a part of it (visible in the Project Explorer).
‘ThisWorkbook’ can store regular macros (similar to the ones that we add-in modules) as well as event procedures. An event procedure is something that is triggered based on an event – such as double-clicking on a cell, or saving a workbook or activating a worksheet.
Any event procedure that you save in this ‘ThisWorkbook’ would be available in the entire workbook, as compared to the sheet level events which are restricted to the specific sheets only.
For example, if you double-click on the ThisWorkbook object in the Project Explorer and copy-paste the below code in it, it will show the cell address whenever you double-click on any of the cells in the entire workbook.
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) MsgBox Target.Address End Sub
While ThisWorkbook’s main role is to store event procedure, you can also use it to refer to the workbook where the code is being executed.
The below code would return the name of the workbook in which the code is being executed.
Sub ThisWorkbookName() MsgBox ThisWorkbook.Name End Sub
The benefit of using ThisWorkbook (over ActiveWorkbook) is that it would refer to the same workbook (the one that has the code in it) in all the cases. So if you use a VBA code to add a new workbook, the ActiveWorkbook would change, but ThisWorkbook would still refer to the one that has the code.
Creating a New Workbook Object
The following code will create a new workbook.
Sub CreateNewWorkbook() Workbooks.Add End Sub
When you add a new workbook, it becomes the active workbook.
The following code will add a new workbook and then show you the name of that workbook (which would be the default Book1 type name).
Sub CreateNewWorkbook() Workbooks.Add MsgBox ActiveWorkbook.Name End Sub
Open a Workbook using VBA
You can use VBA to open a specific workbook when you know the file path of the workbook.
The below code will open the workbook – Examples.xlsx which is in the Documents folder on my system.
Sub OpenWorkbook() Workbooks.Open ("C:UserssumitDocumentsExamples.xlsx") End Sub
In case the file exists in the default folder, which is the folder where VBA saves new files by default, then you can just specify the workbook name – without the entire path.
Sub OpenWorkbook() Workbooks.Open ("Examples.xlsx") End Sub
In case the workbook that you’re trying to open doesn’t exist, you’ll see an error.
To avoid this error, you can add a few lines to your code to first check whether the file exists or not and if it exists then try to open it.
The below code would check the file location and if it doesn’t exist, it will show a custom message (not the error message):
Sub OpenWorkbook()
If Dir("C:UserssumitDocumentsExamples.xlsx") <> "" Then
Workbooks.Open ("C:UserssumitDocumentsExamples.xlsx")
Else
MsgBox "The file doesn't exist"
End If
End Sub
You can also use the Open dialog box to select the file that you want to open.
Sub OpenWorkbook()
If Dir("C:UserssumitDocumentsExamples.xlsx") <> "" Then
Workbooks.Open ("C:UserssumitDocumentsExamples.xlsx")
Else
MsgBox "The file doesn't exist"
End If
End Sub
The above code opens the Open dialog box. When you select a file that you want to open, it assigns the file path to the FilePath variable. Workbooks.Open then uses the file path to open the file.
In case the user doesn’t open a file and clicks on Cancel button, FilePath becomes False. To avoid getting an error in this case, we have used the ‘On Error Resume Next’ statement.
Saving a Workbook
To save the active workbook, use the code below:
Sub SaveWorkbook() ActiveWorkbook.Save End Sub
This code works for the workbooks that have already been saved earlier. Also, since the workbook contains the above macro, if it hasn’t been saved as a .xlsm (or .xls) file, you will lose the macro when you open it next.
If you’re saving the workbook for the first time, it will show you a prompt as shown below:
When saving for the first time, it’s better to use the ‘Saveas’ option.
The below code would save the active workbook as a .xlsm file in the default location (which is the document folder in my system).
Sub SaveWorkbook() ActiveWorkbook.SaveAs Filename:="Test.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled End Sub
If you want the file to be saved in a specific location, you need to mention that in the Filename value. The below code saves the file on my desktop.
Sub SaveWorkbook() ActiveWorkbook.SaveAs Filename:="C:UserssumitDesktopTest.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled End Sub
If you want the user to get the option to select the location to save the file, you can use call the Saveas dialog box. The below code shows the Saveas dialog box and allows the user to select the location where the file should be saved.
Sub SaveWorkbook() Dim FilePath As String FilePath = Application.GetSaveAsFilename ActiveWorkbook.SaveAs Filename:=FilePath & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled End Sub
Note that instead of using FileFormat:=xlOpenXMLWorkbookMacroEnabled, you can also use FileFormat:=52, where 52 is the code xlOpenXMLWorkbookMacroEnabled.
Saving All Open Workbooks
If you have more than one workbook open and you want to save all the workbooks, you can use the code below:
Sub SaveAllWorkbooks() Dim wb As Workbook For Each wb In Workbooks wb.Save Next wb End Sub
The above saves all the workbooks, including the ones that have never been saved. The workbooks that have not been saved previously would get saved in the default location.
If you only want to save those workbooks that have previously been saved, you can use the below code:
Sub SaveAllWorkbooks() Dim wb As Workbook For Each wb In Workbooks If wb.Path <> "" Then wb.Save End If Next wb End Sub
Saving and Closing All Workbooks
If you want to close all the workbooks, except the workbook that has the current code in it, you can use the code below:
Sub CloseandSaveWorkbooks() Dim wb As Workbook For Each wb In Workbooks If wb.Name <> ThisWorkbook.Name Then wb.Close SaveChanges:=True End If Next wb End Sub
The above code would close all the workbooks (except the workbook that has the code – ThisWorkbook). In case there are changes in these workbooks, the changes would be saved. In case there is a workbook that has never been saved, it will show the save as dialog box.
Save a Copy of the Workbook (with Timestamp)
When I am working with complex data and dashboard in Excel workbooks, I often create different versions of my workbooks. This is helpful in case something goes wrong with my current workbook. I would at least have a copy of it saved with a different name (and I would only lose the work I did after creating a copy).
Here is the VBA code that will create a copy of your workbook and save it in the specified location.
Sub CreateaCopyofWorkbook() ThisWorkbook.SaveCopyAs Filename:="C:UserssumitDesktopBackupCopy.xlsm" End Sub
The above code would save a copy of your workbook every time you run this macro.
While this works great, I would feel more comfortable if I had different copies saved whenever I run this code. The reason this is important is that if I make an inadvertent mistake and run this macro, it will save the work with the mistakes. And I wouldn’t have access to the work before I made the mistake.
To handle such situations, you can use the below code that saves a new copy of the work each time you save it. And it also adds a date and timestamp as a part of the workbook name. This can help you track any mistake you did as you never lose any of the previously created backups.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) ThisWorkbook.SaveCopyAs Filename:="C:UserssumitDesktopBackupCopy" & Format(Now(), "dd-mm-yy-hh-mm-ss-AMPM") & ".xlsm" End Sub
The above code would create a copy every time you run this macro and add a date/time stamp to the workbook name.
Create a New Workbook for Each Worksheet
In some cases, you may have a workbook that has multiple worksheets, and you want to create a workbook for each worksheet.
This could be the case when you have monthly/quarterly reports in a single workbook and you want to split these into one workbook for each worksheet.
Or, if you have department wise reports and you want to split these into individual workbooks so that you can send these individual workbooks to the department heads.
Here is the code that will create a workbook for each worksheet, give it the same name as that of the worksheet, and save it in the specified folder.
Sub CreateWorkbookforWorksheets() Dim ws As Worksheet Dim wb As Workbook For Each ws In ThisWorkbook.Worksheets Set wb = Workbooks.Add ws.Copy Before:=wb.Sheets(1) Application.DisplayAlerts = False wb.Sheets(2).Delete Application.DisplayAlerts = True wb.SaveAs "C:UserssumitDesktopTest" & ws.Name & ".xlsx" wb.Close Next ws End Sub
In the above code, we have used two variable ‘ws’ and ‘wb’.
The code goes through each worksheet (using the For Each Next loop) and creates a workbook for it. It also uses the copy method of the worksheet object to create a copy of the worksheet in the new workbook.
Note that I have used the SET statement to assign the ‘wb’ variable to any new workbook that is created by the code.
You can use this technique to assign a workbook object to a variable. This is covered in the next section.
Assign Workbook Object to a Variable
In VBA, you can assign an object to a variable, and then use the variable to refer to that object.
For example, in the below code, I use VBA to add a new workbook and then assign that workbook to the variable wb. To do this, I need to use the SET statement.
Once I have assigned the workbook to the variable, all the properties of the workbook are made available to the variable as well.
Sub AssigntoVariable() Dim wb As Workbook Set wb = Workbooks.Add wb.SaveAs Filename:="C:UserssumitDesktopExamples.xlsx" End Sub
Note that the first step in the code is to declare ‘wb’ as a workbook type variable. This tells VBA that this variable can hold the workbook object.
The next statement uses SET to assign the variable to the new workbook that we are adding. Once this assignment is done, we can use the wb variable to save the workbook (or do anything else with it).
Looping through Open Workbooks
We have already seen a few examples codes above that used looping in the code.
In this section, I will explain different ways to loop through open workbooks using VBA.
Suppose you want to save and close all the open workbooks, except the one with the code in it, then you can use the below code:
Sub CloseandSaveWorkbooks() Dim wb As Workbook For Each wb In Workbooks If wb.Name <> ThisWorkbook.Name Then wb.Close SaveChanges:=True End If Next wb End Sub
The above code uses the For Each loop to go through each workbook in the Workbooks collection. To do this, we first need to declare ‘wb’ as the workbook type variable.
In every loop cycle, each workbook name is analyzed and if it doesn’t match the name of the workbook that has the code, it’s closed after saving its content.
The same can also be achieved with a different loop as shown below:
Sub CloseWorkbooks() Dim WbCount As Integer WbCount = Workbooks.Count For i = WbCount To 1 Step -1 If Workbooks(i).Name <> ThisWorkbook.Name Then Workbooks(i).Close SaveChanges:=True End If Next i End Sub
The above code uses the For Next loop to close all the workbooks except the one that has the code in it. In this case, we don’t need to declare a workbook variable, but instead, we need to count the total number of open workbooks. When we have the count, we use the For Next loop to go through each workbook. Also, we use the index number to refer to the workbooks in this case.
Note that in the above code, we are looping from WbCount to 1 with Step -1. This is needed as with each loop, the workbook gets closed and the number of workbooks gets decreased by 1.
Error while Working with the Workbook Object (Run-time error ‘9’)
One of the most common error you may encounter when working with workbooks is – Run-time Error ‘9’ – Subscript out of range.
Generally, VBA errors are not very informative and often leave it to you to figure out what went wrong.
Here are some of the possible reasons that may lead to this error:
- The workbook that you’re trying to access does not exist. For example, if I am trying to access the fifth workbook using Workbooks(5), and there are only 4 workbooks open, then I will get this error.
- If you’re using a wrong name to refer to the workbook. For example, if your workbook name is Examples.xlsx and you use Example.xlsx. then it will show you this error.
- If you haven’t saved a workbook, and you use the extension, then you get this error. For example, if your workbook name is Book1, and you use the name Book1.xlsx without saving it, you will get this error.
- The workbook you’re trying to access is closed.
Get a List of All Open Workbooks
If you want to get a list of all the open workbooks in the current workbook (the workbook where you’re running the code), you can use the below code:
Sub GetWorkbookNames() Dim wbcount As Integer wbcount = Workbooks.Count ThisWorkbook.Worksheets.Add ActiveSheet.Range("A1").Activate For i = 1 To wbcount Range("A1").Offset(i - 1, 0).Value = Workbooks(i).Name Next i End Sub
The above code adds a new worksheet and then lists the name of all the open workbooks.
If you want to get their file path as well, you can use the below code:
Sub GetWorkbookNames() Dim wbcount As Integer wbcount = Workbooks.Count ThisWorkbook.Worksheets.Add ActiveSheet.Range("A1").Activate For i = 1 To wbcount Range("A1").Offset(i - 1, 0).Value = Workbooks(i).Path & "" & Workbooks(i).Name Next i End Sub
Open the Specified Workbook by Double-clicking on the Cell
If you have a list of file paths for Excel workbooks, you can use the below code to simply double-click on the cell with the file path and it will open that workbook.
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Workbooks.Open Target.Value End Sub
This code would be placed in the ThisWorkbook code window.
To do this:
- Double click on the ThisWorkbook object in the project explorer. Note that the ThisWorkbook object should be in the workbook where you want this functionality.
- Copy and paste the above code.
Now, if you have the exact path of the files that you want to open, you can do that by simply double-clicking on the file path and VBA would instantly open that workbook.
Where to Put the VBA Code
Wondering where the VBA code goes in your Excel workbook?
Excel has a VBA backend called the VBA editor. You need to copy and paste the code into the VB Editor module code window.
Here are the steps to do this:
- Go to the Developer tab.
- Click on the Visual Basic option. This will open the VB editor in the backend.
- In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
- Go to Insert and click on Module. This will insert a module object for your workbook.
- Copy and paste the code in the module window.
You May Also Like the Following Excel VBA Tutorials:
- How to Record a Macro in Excel.
- Creating a User Defined Function in Excel.
- How to Create and Use Add-in in Excel.
- How to Resue Macros by placing it in the Personal Macro Workbook.
- Get the List of File Names from a Folder in Excel (with and without VBA).
- How to Use Excel VBA InStr Function (with practical EXAMPLES).
- How to Sort Data in Excel using VBA (A Step-by-Step Guide).