To save an Excel workbook using VBA, you need to use the SAVE method to write a macro. And in that macro, you need to specify the workbook that you want to save and then use the SAVE method. When you run this code, it works like the keyboard shortcut (Control + S).
- Specify the workbook hat you want to save.
- Type a dot to get the list of all the properties and methods.
- Select the “Save” method out of those or type “Save”
- In the end, run the code to save the workbook.
In this tutorial, we will look at different ways that we can use to save a workbook. So make sure to open the VBA editor from the developer tab to use the code you have in this tutorial.
Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook
Save the ActiveWorkbook
If you want to save the active workbook in that case you can use a code like the following code, instead of specifying the workbook by its name.
ActiveWorkbook.Save
When you use the ActiveWorkbook as the workbook, VBA always refers to the workbook which is active despite in which file you are writing the code.
Save the Workbook where you are Writing Code
If you want to save the file where you are writing the code you need to use “ThisWorkbook” instead of the workbook name.
ThisWorkbook.Save
Save All the Open Workbooks
Here we can use a loop to loop through all the workbooks that are open and save them one by one. Look at the below code.
Sub vba_save_workbook()
'variable to use as a workbook
Dim wb As Workbook
'For each to loop through each open workbook and save it
For Each wb In Workbooks
wb.Save
Next wb
End Sub
The above code uses the FOR EACH loop in each workbook it uses the SAVE method to each file one by one.
Note: If you are trying to save a workbook with the SAVE method that is not saved already, Excel will show a dialog box to ask for your permission to save that file, and then you need to choose if you want to save that file on the default location in the default format.
Now here’s the point: As you are using a macro to save the workbook, that file should be saved in the macro-enabled format and the best way to deal with this situation is to use the SAVE AS method (we’ll see in the next section of this tutorial).
To SAVE a file that is not saved yet, using VBA, you need to use the SAVE AS method. In this method, you can define the file name and the path where you want to save the file, and apart from that, there are ten more arguments that you can define.
expression.SaveAs (FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)
In the following code, you don’t have any argument with the “SAVE AS” method.
When you run this code, it asks you a few things, like, which format you want to use to save the file, do you want to replace the existing file that is already saved with the same name. So it’s better to define the use of some of the arguments.
Save As File on the Current Location
By default, VBA uses the current location to save the file. When you write code with the SAVE AS method and just specify the name that file straight goes to the current folder. You can see in the following code where you have the which saves the active workbook.
Sub save_as_file()
ActiveWorkbook.SaveAs Filename:="myNewWorkbook"
End Sub
Save As File on a Specific Location
The filename argument also allows you to use the location path in case you want to use a different location to save the file.
Sub save_as_file()
ActiveWorkbook.SaveAs _
Filename:="C:UsersDellDesktopmyNewBook"
End Sub
In the above code, you have the path in the FileName argument and VBA uses that path to the file.
Note: You can also use this method to check if a workbook exists in a folder or not before you use the SAVE AS method to save it on a particular location and you can learn more about SAVE AS method from here.
More on VBA Workbooks
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 Create New Workbook (Excel File)
- VBA Workbook
In this Article
- Save Workbook – VBA
- Save a Specified Workbook
- Save the Active Workbook
- VBA Coding Made Easy
- Save the Workbook Where the Code is Stored
- Save all Open Workbooks
- Save all open workbooks that were not opened ReadOnly
- Save a workbook defined by a variable
- Save a workbook defined by a string variable
- Save a workbook defined by the order it was opened.
- Save a workbook based on a cell value
- Save As – VBA
- SaveAs Syntax:
- Save As Syntax Examples:
- Workbook Save As – Same Directory
- Workbook Save As – New Directory
- Workbook Save As – New Directory, Specify File Extension
- Workbook Save As – New Directory, Specify File Extension – Alt Method
- Workbook Save As – Add Password to Open File
- Workbook Save As – Add Password for Write Privileges
- Workbook Save As – Read-Only Recommended
- Other Save As Examples
- Create Save As Dialog Box
- Create Save As Dialog Box with Default File Name Provided
- Create Save As Dialog Box with Default File Name Provided
- Create & Save New Workbook
- Disable Save Alerts
This VBA Tutorial covers how to save a file using the Save and Save As commands in VBA.
Save Workbook – VBA
The VBA Save command saves an Excel file similarly to clicking the Save icon or using the Save Shortcut (CTRL + S).
Save a Specified Workbook
To save a workbook, reference the workbook object and use the Save command.
Workbooks("savefile.xlsm").Save
Save the Active Workbook
Note: This is the current active workbook from with in the VBA code, which is different from ThisWorkbook which contains the running code.
ActiveWorkbook.Save
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!
Save the Workbook Where the Code is Stored
ThisWorkbook.save
Save all Open Workbooks
This will loop through all open workbooks, saving each one.
Dim wb as workbook
For Each wb In Application.Workbooks
wb.Save
Next wb
Save all open workbooks that were not opened ReadOnly
Note: opening a workbook in ReadOnly mode prevents the file from being saved.
To save the file you will need to use Save As and save the file with a different name.
Dim wb as workbook
For Each wb In Application.Workbooks
If not wb.ReadOnly then
wb.Save
End if
Next wb
Save a workbook defined by a variable
This will save a workbook that was assigned to a workbook object variable.
Dim wb as workbook
set wb = workbooks("savefile.xlsm")
wb.save
Save a workbook defined by a string variable
This will save a workbook that’s name was saved to a string variable.
Dim wbstring as string
wbstring = "savefile.xlsm"
workbooks(wbstring).save
Save a workbook defined by the order it was opened.
Note: The first workbook opened would have 1, the second 2, etc.
workbooks(1).save
VBA Programming | Code Generator does work for you!
Save a workbook based on a cell value
This will save a workbook that’s name is found in a cell value.
Dim wbstring as string
wbstring = activeworkbook.sheets("sheet1").range("wb_save").value
workbooks(wbstring).save
Save As – VBA
The VBA Save As command saves an Excel file as a new file, similar to clicking the Save As icon or using the Save As Shortcut (Alt > F > A).
Above, we identified all the ways to specify which workbook to save. You can use those exact same methods to identify workbooks when using Save As.
Save As behaves similarly to Save, except you also need to specify the name of the new file.
In fact, Save As has many potential variables to define:
SaveAs Syntax:
workbook object .SaveAs(FileName, FileFormat, Password, WriteResPassword, _
ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, _
AddToMru,TextCodepage, TextVisualLayout, Local)
A full description of all of the SaveAs arguments is included below. For now we will focus on the most common examples.
Note: These arguments can be entered as string with parenthesis or as defined variables.
Save As Syntax Examples:
Workbook Save As – Same Directory
ActiveWorkbook.SaveAs Filename:= "new"
or
ActiveWorkbook.SaveAs "new"
or
Dim wbstring as string
wbstring = "new"
ActiveWorkbook.SaveAs Filename:= wbstring
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Workbook Save As – New Directory
ActiveWorkbook.SaveAs Filename:= "C:new"
or
Dim wbstring as string
wbstring = "C:new"
ActiveWorkbook.SaveAs Filename:= wbstring=
Workbook Save As – New Directory, Specify File Extension
ActiveWorkbook.SaveAs Filename:= "C:new.xlsx"
or
Dim wbstring as string
wbstring = "C:new.xlsx"
ActiveWorkbook.SaveAs Filename:= wbstring
Workbook Save As – New Directory, Specify File Extension – Alt Method
You can also specify the file format in it’s own argument.
.xlsx = 51 '(52 for Mac)
.xlsm = 52 '(53 for Mac)
.xlsb = 50 '(51 for Mac)
.xls = 56 '(57 for Mac)
ActiveWorkbook.SaveAs Filename:= "C:new", FileFormat:= 51
Workbook Save As – Add Password to Open File
ActiveWorkbook.SaveAs Filename:= "C:new.xlsx", Password:= "password"
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Workbook Save As – Add Password for Write Privileges
If correct password is not supplied then workbook opens as Read-Only
ActiveWorkbook.SaveAs Filename:= "C:new.xlsx", WriteRes:= "password"
Workbook Save As – Read-Only Recommended
TRUE to display a message box, recommending that the file is opened read-only.
ActiveWorkbook.SaveAs Filename:= "C:new.xlsx", ReadOnlyRecommended:= TRUE
Other Save As Examples
Create Save As Dialog Box
This Generates the Save As Dialog Box, prompting the user to Save the file.
Keep in mind that this simple code may not be appropriate in all cases.
Application.GetSaveAsFilename
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Create Save As Dialog Box with Default File Name Provided
Application.GetSaveAsFilename InitialFilename:="test.xlsx"
Create Save As Dialog Box with Default File Name Provided
Application.GetSaveAsFilename InitialFilename:="test.xlsx"
Create & Save New Workbook
This will create a new workbook and immediately save it.
Dim wb As Workbook
Set wb = Workbooks.Add
Application.DisplayAlerts = False
wb.SaveAs Filename:=”c:Test1.xlsx”
Application.DisplayAlerts = True
Disable Save Alerts
As you work with saving in VBA, you may come across various Save Warnings or Prompts. To disable warnings, add this line of code:
Application.DisplayAlerts=False
and to re-able alerts:
Application.DisplayAlerts=True
Содержание
- VBA Save File – 20 Easy Examples
- Save Workbook – VBA
- Save a Specified Workbook
- Save the Active Workbook
- VBA Coding Made Easy
- Save the Workbook Where the Code is Stored
- Save all Open Workbooks
- Save all open workbooks that were not opened ReadOnly
- Save a workbook defined by a variable
- Save a workbook defined by a string variable
- Save a workbook defined by the order it was opened.
- Save a workbook based on a cell value
- Save As – VBA
- SaveAs Syntax:
- VBA Tips & Tricks
- Pages
- Sunday, March 02, 2008
- Save and Reopen all Workbooks (Excel VBA)
- 2 comments:
- Saving Files in Excel VBA
- Saving Files in Excel VBA
- How to Run a Code in Visual Basic Editor?
- Save Workbook or a File using Save option
- Save Active Workbook
- Save Specific Workbook
- Save All Open Workbooks
- Save the workbook using Index
- Save As in Excel VBA
- Syntax for Save As command
- Workbook Save As – Same Directory
- VBA Open / Close Workbook
- Open a Workbook in VBA
- Open Workbook From Path
- Open Workbook – ActiveWorkbook
- Open Workbook and Assign to a Variable
- Workbook Open File Dialog
- Open New Workbook
- VBA Coding Made Easy
- Open New Workbook To Variable
- Open Workbook Syntax
- Open Workbook Read-Only
- Open Password Protected Workbook
- Open Workbook Syntax Notes
- Close a Workbook in VBA
- Close Specific Workbook
- Close Active Workbook
- Close All Open Workbooks
- Close First Opened Workbook
- Close Without Saving
- Save and Close Without Prompt
- Other Workbook Open Examples
- Open Multiple New Workbooks
- Open All Excel Workbooks in a Folder
- Check if a Workbook is Open
- Workbook_Open Event
- Open Other Types of Files in VBA
- Open a Text file and Read its Contents
- Open a Text File and Append to it
- Opening a Word File and Writing to it
- VBA Code Examples Add-in
- Using Workbook Object in Excel VBA (Open, Close, Save, Set)
- Referencing a Workbook using VBA
- Using Workbook Names
- Using Index Numbers
- Using ActiveWorkbook
- Using ThisWorkbook
- Creating a New Workbook Object
- Open a Workbook using VBA
- Saving a Workbook
- Saving All Open Workbooks
- Saving and Closing All Workbooks
- Save a Copy of the Workbook (with Timestamp)
- Create a New Workbook for Each Worksheet
- Assign Workbook Object to a Variable
- Looping through Open Workbooks
- Error while Working with the Workbook Object (Run-time error ‘9’)
- Get a List of All Open Workbooks
- Open the Specified Workbook by Double-clicking on the Cell
- Where to Put the VBA Code
VBA Save File – 20 Easy Examples
In this Article
This VBA Tutorial covers how to save a file using the Save and Save As commands in VBA.
Save Workbook – VBA
The VBA Save command saves an Excel file similarly to clicking the Save icon or using the Save Shortcut (CTRL + S).
Save a Specified Workbook
To save a workbook, reference the workbook object and use the Save command.
Save the Active Workbook
Note: This is the current active workbook from with in the VBA code, which is different from ThisWorkbook which contains the running code.
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!
Save the Workbook Where the Code is Stored
Save all Open Workbooks
This will loop through all open workbooks, saving each one.
Save all open workbooks that were not opened ReadOnly
Note: opening a workbook in ReadOnly mode prevents the file from being saved.
To save the file you will need to use Save As and save the file with a different name.
Save a workbook defined by a variable
This will save a workbook that was assigned to a workbook object variable.
Save a workbook defined by a string variable
This will save a workbook that’s name was saved to a string variable.
Save a workbook defined by the order it was opened.
Note: The first workbook opened would have 1, the second 2, etc.
Save a workbook based on a cell value
This will save a workbook that’s name is found in a cell value.
Save As – VBA
The VBA Save As command saves an Excel file as a new file, similar to clicking the Save As icon or using the Save As Shortcut (Alt > F > A).
Above, we identified all the ways to specify which workbook to save. You can use those exact same methods to identify workbooks when using Save As.
Save As behaves similarly to Save, except you also need to specify the name of the new file.
In fact, Save As has many potential variables to define:
SaveAs Syntax:
A full description of all of the SaveAs arguments is included below. For now we will focus on the most common examples.
Note: These arguments can be entered as string with parenthesis or as defined variables.
Источник
VBA Tips & Tricks
Welcome to VBA Tips & Tricks. All VBA related information will be posted on this blog. Of late, VBA has been disregarded by many software professionals for .Net, c# and other technologies. This blog will also post articles related to them too Happy reading
Pages
Sunday, March 02, 2008
Save and Reopen all Workbooks (Excel VBA)
Save All Open Workbooks and Re-open them using VBA
Use SaveWorkspace method to save the current workspace and use the Open method to open the files again
Application.SaveWorkspace «C:New FolderTempWorkSpace.XLW»
‘ Do my work here without anyother workbooks
Workbooks.Open «C:New FolderTempWorkSpace.XLW»
The files in the application will be saved and re-opened using Open method
Hi. This is exactly what I want to do. Did I understand something wrong?
This code will not work for workbooks within the same workbook.
Execution ends at the «Workbooks.Close» statment.
Workbooks.Close will close all open workbooks in that particular Excel instance.
If you are using this command from an Open Workbook, it will close that too. If the workbook is not saved, it might prompt for confirmation
If the DisplayAlerts is set to false, you can avoid the prompt
Источник
Saving Files in Excel VBA
In this post, you will be learning about Saving Files in Excel VBA and the different options associated with it.
Saving Files in Excel VBA
You can save a file in Excel VBA using two different methods,
Read along to know more about each option.
How to Run a Code in Visual Basic Editor?
As you know, to run the VBA code in Excel,
- Open the Visual Basic Editor (Alt + F11),
- Click on Insert a new module.
- Enter the code, save it and run it.
Save Workbook or a File using Save option
Let’s see the different ways of saving a workbook using Excel VBA using the save workbook option.
Save Active Workbook
To save an active workbook in Excel VBA, enter the following code in the module and click run.
Code
Save Specific Workbook
If you want to save a specific workbook, you need to specify the name of the workbook in the below code and run it.
Code
Save All Open Workbooks
To save the all open workbook in Excel VBA, enter the following code in the module and click run.
Code
Save the workbook using Index
To save workbook using index in Excel VBA, enter the following code in the module and click run.
This code consists of a loop, hence while running this code, it saves all the other workbooks other than the one with this code.
Code
Save As in Excel VBA
The Save As command saves an Excel file as a new file, similar to clicking the Save As icon. Save As works similarly to the Save option, except you need to specify the name of the new file.
Syntax for Save As command
workbook object .SaveAs(FileName, FileFormat, Password, WriteResPassword, _
ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, _
AddToMru,TextCodepage, TextVisualLayout, Local)
The bellow are the different ‘save as’ options available.
Workbook Save As – Same Directory
To save a file in the same directory using save as option,
Источник
VBA Open / Close Workbook
In this Article
In this tutorial, you will learn how to use VBA to open and close Excel Workbooks and other types of Files in several ways.
VBA allows you to open or close files using the standard methods .Open and .Close.
If you want to learn how to check if a file exists before attempting to open the file, you can click on this link: VBA File Exists
Open a Workbook in VBA
Open Workbook From Path
If you know which file you want to open, you can specify its full path name in the function. Here is the code:
This line of the code opens “Sample file 1” file from the “VBA Folder”.
Open Workbook – ActiveWorkbook
When you open a workbook, it automatically becomes the ActiveWorkbook. You can reference the newly opened workbook like so:
When you reference a sheet or range and omit the workbook name, VBA will assume you are referring to the ActiveWorkbook:
Open Workbook and Assign to a Variable
You can also open a workbook and assign it directly to an object variable. This procedure will open a workbook to the wb variable and then save the workbook.
Assigning workbooks to variables when they open is the best way to keep track of your workbooks
Workbook Open File Dialog
You can also trigger the workbook Open File Dialog box. This allows the user to navigate to a file and open it:
As you can see in Image 1, with this approach users can choose which file to open. The Open File Dialog Box can be heavily customized. You can default to a certain folder, choose which types of files are visible (ex. .xlsx only), and more. Read our tutorial on the Open File Dialog Box for detailed examples.
Open New Workbook
This line of code will open a new workbook:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Open New Workbook To Variable
This procedure will open a new workbook, assigning it to variable wb:
Open Workbook Syntax
When you use Workbooks.Open you might notice that there are many options available when opening the workbook:
The Filename is required. All other arguments are optional – and you probably won’t need to know most of the other arguments. Here are the two most common:
Open Workbook Read-Only
When workbook is opened read-only, you can’t save over the original file. This prevents the file from being edited by the user.
Open Password Protected Workbook
A workbook might be password-protected. Use this code to open the password-protected workbook:
Open Workbook Syntax Notes
Notice that in the image above, we included a parenthesis “(” to show the syntax. If you use parenthesis when working with Workbooks.Open, you must assign the workbook to a variable:
Close a Workbook in VBA
Close Specific Workbook
Similarly to opening a workbook, there are several ways to close a file. If you know which file you want to close, you can use the following code:
This line of code closes the file “Sample file 1” if it’s opened. If not, it will return an error, so you should take care of error handling.
Close Active Workbook
If you want to close the Workbook which is currently active, this line of code will enable you to do that:
Close All Open Workbooks
To close all open Workbooks, you can simply use this code:
Close First Opened Workbook
This will close the first opened/created workbook:
Replace 1 with 2 to close the second opened / created workbook and so on.
Close Without Saving
This will close a Workbook without saving and without showing the save prompt:
Save and Close Without Prompt
Similarly this will save and close a Workbook without showing the save prompt:
Note: There are several other ways to indicate whether to save or not save a Workbook and also whether to show prompts or not. This is discussed in more detail here.
Other Workbook Open Examples
Open Multiple New Workbooks
This procedure will open multiple new workbooks, assigning the new workbooks to an array:
Open All Excel Workbooks in a Folder
This procedure will open all Excel Workbooks in a folder, using the Open File Dialog picker.
Check if a Workbook is Open
Workbook_Open Event
VBA Events are “triggers” that tell VBA to run certain code. You can set up workbook events for open, close, before save, after save and more.
Read our Workbook_Open Event tutorial to learn more about automatically running macros when a workbook is opened.
Open Other Types of Files in VBA
You can use the VBA to open other types of files with VBA – such as txt or Word files.
Open a Text file and Read its Contents
The VBA open method allows you to read or write to the file once you have opened it. To read the contents of a file, we can open the file for INPUT.
The code above will open the text file “test.txt” and then it will read the entire contents of the file to the strBody variable. Once you have extracted the file data into the strBody variable, you can use it for what you require. Using the Debug.Print command above enables us to see the contents of the strBody variable in the Immediate window in the VBE.
Open a Text File and Append to it
We can also open a text file in VBA, and then append to the bottom of the file using the Append method.
The above code will open the text file and then append 2 lines of text to the bottom of the file using the #intFile variable (the # sign is the key!). The code then closes the file.
Opening a Word File and Writing to it
We can also use VBA in Excel to open a Word file.
This code will open a copy of Word, and then open the document test.docx.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Using Workbook Object in Excel VBA (Open, Close, Save, Set)
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.
This Tutorial Covers:
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:
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).
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).
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.
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.
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.
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).
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.
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.
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.
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).
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.
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.
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):
You can also use the Open dialog box to select the file that you want to open.
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:
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).
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.
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.
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:
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:
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:
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.
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.
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.
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.
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:
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:
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:
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:
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.
This code would be placed in the ThisWorkbook code window.
- 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:
Источник
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).
This tutorial shows how to save all open Excel files at once using VBA
METHOD 1. Save all open Excel files at once using VBA
VBA
Sub Save_all_excel_files()
Dim wb As Workbook
For Each wb In Application.Workbooks
If Not wb.ReadOnly Then
wb.Save
End If
Next
End Sub
NOTES
Note 1: This VBA code will save all open excel files in their existing locations at once.
Related Topic | Description | Related Topic and Description |
---|---|---|
Create and Save a new workbook | How to create and save a new workbook using VBA | |
Save an Excel workbook | How to save an Excel workbook |