VBA Open / Close Workbook

Associated Files Download Links

VBA allows you to open or close files using the standard methods .Open and .Close. In this tutorial, you will learn how to open and close a Workbook in several ways.

If you want to learn how to check if a file exists, you can click on this link: VBA File Exists


Open a Workbook in VBA

There are several ways to open a file in VBA. Below we will show simple examples of each.

Open Workbook From Path

If you know which file you want to open, you can specify its name in the function. Here is the code:

This line of the code opens “Sample file 1” file from the “VBA Folder”. You must specify the full path of the file.


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:

vba open close file

Image 1. Open the file


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.

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.



You may also like some of this related content...

VBA allows you to check if a file or folder exists by using the Dir
VBA allows you to rename an existing file, using the Name command. In this tutorial,
VBA allows you to delete an existing file, using the Kill command. In this tutorial,
VBA allows you to choose a file to open using the Application.GetOpenFilename method. In this
VBA allows you to copy a file, using the FileSystemObject. In this tutorial, you will