Saving workbook in excel vba

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).

  1. Specify the workbook hat you want to save.
  2. Type a dot to get the list of all the properties and methods.
  3. Select the “Save” method out of those or type “Save”
  4. 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

If you’ve worked with Excel before, you’re probably quite familiar with 2 basic commands for saving workbooks:

  • Save.
  • Save As.

Excel VBA Tutorial about how to save workbooks and filesIt may not surprise you to know that, when working with VBA, you can carry out these same activities.

In fact, knowing how to save Excel workbooks using VBA is essential. As you work with Visual Basic for Applications, you’ll notice that saving workbooks is one of the most important things your macros can do.

Due to the importance of knowing how to save workbooks using VBA, this Excel tutorial focuses on this particular topic:

How to save an Excel workbook using VBA.

In addition to providing some examples of VBA code that you can use to save workbooks, I explain the basics surrounding 4 VBA methods that you’re likely to encounter and use constantly while saving workbooks. The following table of contents shows the specific topics that I explain in this Excel tutorial:

This Excel tutorial doesn’t cover the topic of saving an Excel workbook as PDF using VBA. I explain how to export an Excel file to PDF using macros, and provide several code examples, here.

Let’s start taking a look at the basic ways to save an Excel workbook using VBA.

How To Save An Excel Workbook Using the Workbook.Save VBA Method

The most basic method to save Excel workbooks using VBA is the Workbook.Save method. Workbook.Save saves the relevant workbook.

In other words, the Workbook.Save method is, roughly, the VBA equivalent of the Save command in Excel.

The syntax of the Workbook.Save method is as follows:

expression.Save

Where “expression” is the relevant Workbook object you want to save.

Let’s take a look at an example to make this clearer. The following macro, named “Save_Workbook”, saves the current active workbook:

ActiveWorkbook.Save macro

This Excel VBA Save Workbook Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the Save_Workbook macro). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Notice that the macro has only 1 statement which follows the general syntax of the Workbook.Save method explained above:

ActiveWorkbook.Save

In this case, ActiveWorkbook is a simplified reference to the Application.ActiveWorkbook property. This property returns a Workbook object, as required by the Workbook.Save method. The workbook that is returned by the ActiveWorkbook property is, more precisely, the workbook in the current active window.

In summary, the sample Save_Workbook macro above simply saves the current active Excel workbook.

Just as when working directly with Excel, the Save method is an important command/method that is relatively easy and straightforward to execute. However, it doesn’t allow you to determine much in connection with the way the relevant Excel workbook is saved. The workbook is saved and that’s pretty much it.

When working directly in Excel, you use the Save As command if you want to be able to determine more about the way the actual saving of a workbook takes place. Things work in a similar fashion within Visual Basic for Applications.

More precisely, when working with Visual Basic for Applications, you can use the SaveAs method for these purposes. So let’s take a look at:

How To Save An Excel Workbook Using The Workbook.SaveAs VBA Method

The arguments or parameters of a method are what allows you to determine the characteristics of the action that a particular method performs.

As explained above, the Workbook.Save method doesn’t have any parameters. As a consequence, you can’t really determine much about how the relevant workbook is saved.

The Workbook.SaveAs method is different. Its 12 parameters allow you to further determine several aspects about the way in which an Excel workbook is saved. In other words, Workbook.SaveAs is more flexible and complex than Workbook.Save.

Workbook.SaveAs is, roughly speaking, the VBA equivalent of the Save As command in Excel. Therefore, it allows you to save a workbook in a particular file. The complete syntax of the Workbook.SaveAs method is as follows:

expression.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode,ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)

“expression” is, just as in the case of the Workbook.Save method above, the relevant Workbook object.

All of the parameters (which appear within parentheses) of the SaveAs method are optional. However, in order to understand what this method can help you with, I explain these parameters below.

However, as usual, I use a practical macro example for purposes of illustrating how Workbook.SaveAs works. So let’s start by taking a look at the basic VBA code of the macro example:

How To Save An Excel Workbook With A New Name Using The Workbook.SaveAs Method

The following piece of VBA code saves the current active workbook with a new name provided by the user.

Dim workbook_Name As Variant

workbook_Name = Application.GetSaveAsFilename

If workbook_Name <> False Then

ActiveWorkbook.SaveAs Filename:=workbook_Name

End If

The following screenshot shows the VBA code behind the example macro (called “Save_Workbook_NewName”) which is included in the Excel workbook that accompanies this Excel VBA Save Workbook Tutorial. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

VBA code with ActiveWorkbook.SaveAs

This macro can be divided in the following 3 parts:

Save workbook VBA code with sections

Let’s take a quick look at each of these parts to understand how the Save_Workbook_NewName macro works:

Part #1: Dim workbook_Name As Variant

This statement simply declares a variable named workbook_Name. The variable is of the Variant data type.

Even though Variant variables are sometimes undesirable, in this particular case that’s not necessarily the case. A Variant variable allows the GetSaveAsFilename (which I introduce below) to be quite flexible.

As implied by its name, and made evident by the following parts of the macro, the purpose of the workbook_Name variable is to store the new name of the saved Excel workbook.

Part #2: workbook_Name = Application.GetSaveAsFilename

This statement assigns a value to the workbook_Name variable. Which value is actually assigned is determined by the Application.GetSaveAsFilename method, which I explain thoroughly below.

At its most basic level, the GetSaveAsFilename method, does the following 2 things:

  • Step #1: Displays the Save As dialog box.

    You’re probably quite familiar with this dialog box, as it’s the one Excel displays when you execute the Save As command.

    Save As dialog displayed by GetSaveAsFilename

  • Step #2: Once the user has provided a file name through the Save As dialog box, GetSaveAsFilename gets that particular name.

    This is the name that the whole statement we’re analyzing assigns to the variable workbook_Name.

Note that the Application.GetSaveAsFilename method doesn’t actually save a file. It simply gets a name.

To actually save the file using the name provided by the GetSaveAsFilename method, you usually rely on the Workbook.SaveAs method. This method is used in the last part of the Save_Workbook_NewName macro:

Part #3: If workbook_Name <> False Then ActiveWorkbook.SaveAs Filename:=workbook_Name End If

This is an If… Then… Else statement. These type of statements conditionally execute a particular group of statement depending on whether a condition is met or not. The statement begins with the word If. The whole block finishes with the End If statement.

In the case of the Save_Workbook_NewName macro, the If… Then… Else statement proceeds as follows:

Step #1: Test Whether workbook_Name <> False.

The first part of the If… Then… Else statement carries out a logical test. This logical test seeks to confirm whether the variable workbook_Name has a value that is different from (<>) the logical value False.

If the value of workbook_Name isn’t False, the logical test (workbook_Name <> False) evaluates to True. In such a case, the statements within the If… Then… Else are executed.

However, if the value of workbook_Name is equal to the Boolean value False, the logical test evaluates to False. In this case, the conditional statements aren’t executed.

For purposes of this logical test, the value of the variable workbook_Name is that assigned in the previous part. Therefore, the value depends on the input given by the user when the Save As dialog box is displayed. More precisely:

  • If the user cancels the Save As dialog box, the value of workbook_Name is False.
  • If the user provides a file name through the Save As dialog box, the value of the workbook_Name variable is (generally) that assigned by the user.

In other words:

  • If the user provides a file name:
    • The logical test carried out by the first part of the If… Then… Else statement is True; and
    • The conditional statements that follow are executed.
  • If the user cancels the Save As dialog box (by, for example, clicking on the Cancel button):
    • The logical test is False; and
    • The conditional statements within the If… Then… Else statement aren’t executed.

Step#2: Execute The Statement ActiveWorkbook.SaveAs Filename:=workbook_Name If The Tested Condition Is True.

You already know that, roughly speaking, the logical test workbook_Name <> False returns True if the user has assigned a file name through the Save As dialog box.

In such case, the following statement is executed:

ActiveWorkbook.SaveAs Filename:=workbook_Name

This is where the Workbook.SaveAs method comes into play. This statement does the following:

  • Step #1: Uses the Application.ActiveWorkbook property to return the workbook in the current active window.
  • Step #2: Saves the active workbook in a file whose name is that given by the user through the Save As dialog displayed by the GetSaveAsFilename method.

In this particular case, only 1 argument of the Workbook.SaveAs method is used: Filename. The Filename argument, as implied by its name, allows you to specify the name of the saved workbook.

I explain more about the Filename argument, and the other arguments of the SaveAs method, in the sections below.

If the tested condition isn’t true, no further statements are executed. In other words, the workbook isn’t saved when the used has cancelled the Save As dialog box.

The Workbook.SaveAs Method: Parameters

The following table introduces the 10 most important optional parameters of the Workbook.SaveAs method:

Position Name Description
1 Filename Name of saved workbook.
2 FileFormat File format for saved workbook.
3 Password Protection password for saved workbook
4 WriteResPassword Write-reservation password for saved workbook.
5 ReadOnlyRecommended Determines whether workbook is saved as read-only recommended.
6 CreateBackup Determines whether a backup file of the saved workbook is created.
7 AccessMode Determines the access mode of the saved workbook.
8 ConflictResolution Applies only if saved workbook is shared.

Determines how conflicts that show up when saving are resolved.

9 AddToMru Determines whether saved workbook is added to list of recently used files.
12 Local Determines whether the workbook is saved against the language of Excel (usually local) or VBA (usually US-English).

2 parameters of the SaveAs method (#10, TextCodepage and #11, TextVisualLayout) aren’t included in the table above nor explained below. According to Microsoft’s Official Documentation (at the time of writing), both of these parameters are ignored.

Let’s take a closer look at each of the individual arguments of Workbook.SaveAs:

Argument #1: Filename

As implied by its name, you use the Filename argument of the Workbook.SaveAs method to specify the name of the saved workbook.

When working with the Filename argument, you can either:

  • Specify the full file path; or
  • Don’t specify the file path.

If you don’t specify the file path, Excel saves the workbook in the current folder.

For most users, specifying the file path isn’t very convenient. You (or the user) need to specify accurate file paths, names and extensions. The approach is tedious and error prone.

This is the main reason why the Application.GetSaveAsFilename used in the Save_Workbook_NewName is so helpful: it allows the user to browse the different folders and easily specify the full file path and name of the saved Excel workbook.

The initial basic version of the Save_Workbook_NewName macro uses the Filename argument, as shown in the screenshot below:

VBA code saves workbook with Filename argument

Argument #2: FileFormat

You can use the FileFormat argument of the Workbook.SaveAs method to specify the file format of the saved file.

If you don’t use the FileFormat argument, Excel determines the file format as follows:

  • In the case of workbooks that already exist, the workbook is saved using the same file format as the last time.
  • If the workbook is new, the workbook is saved using the format of the Excel version you’re using.

Even though this parameter (as all other arguments of the SaveAs method) is optional, you may want to develop the habit of using it.

You specify a particular file format using the XlFileFormat enumeration. The Microsoft Developer Network lists more than 50 different possible values.

In practice, you’re unlikely to need/use so many different formats. In fact, some of the formats that are listed at the Microsoft Developer Network are not supported in the more recent versions of Excel.

Therefore, I provide a basic overview and breakdown of the XlFileFormat values that you may actually encounter. Even though this list is much shorter than that at the Microsoft Developer Network, you’re still likely to use only a subset of the values I explain below.

The following are the 4 main file formats in Excel 2007-2013:

  • 50: xlExcel12.
  • 51: xlOpenXMLWorkbook.
  • 52: xlOpenXMLWorkbookMacroEnabled.
  • 56: xlExcel8.

As a general rule, it’s better to use the FileFormat values (numbers) instead of the names. The reason for this is that this avoids some compilation problems whenever you execute the relevant macro in an older version of Excel that may not recognize the name.

So let’s a look at some of the values that the FileFormat argument can take:

Value Name Description
Add-Ins And Templates
17 xlTemplate / xlTemplate8 Template / Template 8.

Generally used in versions between Excel 97 and Excel 2003.

18 xlAddIn / xlAddIn8 Excel 1997 to 2003 Add-In.
53 xlOpenXMLTemplateMacroEnabled Macro-Enabled Open XML template.
54 xlOpenXMLTemplate Open XML template.
55 xlOpenXMLAddIn Open XML Add-In.
Text Files
-4158 xlCurrentPlatformText Text file format for platform in which workbook is saved.
2 xlSYLK Symbolic Link Format file.

Only the active sheet is saved.

6 xlCSV CSV (comma-separated values) text file format.
9 xlDIF Data Interchange Format file.

Only saves the current active sheet.

19 xlTextMac Mac text file format. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlTestMac saves only the active sheet.

20 xlTextWindows Windows text file format. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlTestWindows saves only the active sheet.

21 xlTextMSDOS MSDOS text file format. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlTestMSDOS saves only the active sheet.

22 xlCSVMac CSV file format for Mac platform. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlCSVMac saves only the active sheet.

23 xlCSVWindows CSV file format for Windows platform. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlCSVWindows saves only the active sheet.

24 xlCSVMSDOS CSV file format for MS-DOS platform. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlCSVMSDOS saves only the active sheet.

36 xlTextPrinter Formatted text file.

Only saves the current active worksheet.

42 xlUnicodeText Unicode text file format.
Spreadsheets (Excel and Others)
-4143 xlWorkbookNormal Excel workbook file format.
39 xlExcel5 / xlExcel7 Excel versions from 1993 (Excel 5.0) and 1995 (Excel 7.0).
43 xlExcel9795 Excel versions from 1995 and 1997.

However, as explained by author Richard Mansfield in Mastering VBA for Microsoft Office 2013, this file format is generally compatible with Excel 95 and later versions.

46 xlXMLSpreadsheet XML spreadsheet file format.

Generally used in Excel 2003.

50 xlExcel12 Excel 2007 version.
51 xlOpenXMLWorkbook / xlWorkbookDefault Open XML workbook / Workbook default file format.
52 xlOpenXMLWorkbookMacroEnabled Macro-Enabled Open XML workbook.
56 xlExcel8 Excel version from 1997.
60 xlOpenDocumentSpreadsheet Open Document Spreadsheet file format.

OpenDocument Spreadsheet files can be opened using spreadsheet applications that use the OpenDocument Spreadsheet format. Examples of such applications are Google Sheets, Open Office Calc and Excel itself.

Formatting may be affected when saving or opening Open Document Spreadsheet files.

61 (&H3D) xlOpenXMLStrictWorkbook ISO Strict Open XML file format.
Clipboard Files
44 xlHtml HTML / webpage file format.

If you save the Excel workbook to a CSV or text file format, the following 2 things happen:

  • Excel selects the code page to use by checking the system locale configuration in the computer where the workbook is saved. The code page used is the one corresponding to the language for the system locale in use. In Windows 10, you can find these settings by going to Settings > Time & Language > Region & Language.
  • Excel saves the file in logical layout. This is relevant, in particular, when working with files containing bi-directional text, where text may be in different directions (left-to-right and right-to-left). Whenever text in one direction is embedded within text in the other direction, the logical layout saves the file in such a way that the reading order is correct for all languages being used, regardless of their directionality. Then, when such a file is opened later, all the text within the file is (generally) displayed in the appropriate direction. This direction is determined by the character value ranges of the code page being used.

Let’s go back to the sample Save_Workbook_NewName. The following screenshot shows how the VBA code of this macro looks like when I add the FileFormat argument and set its value to 52 (Macro-Enabled Open XML workbooks).

VBA code saves workbook with FileFormat argument

Argument #3: Password

The Password argument of the Workbook.SaveAs method allows you to (as you may expect) enter a password to protect the saved Excel workbook.

The Password argument has the following 3 main characteristics:

  • Is a string.
  • Is case-sensitive.
  • Its maximum length is 15 characters.

The following screenshot shows the VBA code behind the Save_Workbook_NewName macro with a password. In this case, the password is “Excel Tutorial”.

VBA code to save workbook with Password argument

If you save a workbook using a macro such as the above, next time anyone (you or another user) tries to open the Excel workbook, Excel displays the Password dialog.

Password dialog box generated by VBA

If the wrong password is entered, Excel doesn’t open the workbook. Instead, it displays a warning.

Excel warns about incorrect password

Argument #4: WriteResPassword

The WriteResPassword parameter of the Workbook.SaveAs method is, in some ways, similar to the Password argument that I explain above. However, Password and WriteResPassword differ in one essential characteristic:

They protect different things.

As explained above, Password protects the workbook. If you (or the relevant user) fail to provide the correct password, Excel doesn’t open the workbook.

WriteResPassword protects the write-reservation characteristic of the workbook. To see what this is, and how it works in practice, I add the WriteResPassword argument to the Save_Workbook_NewName macro. The password for these purposes is “Excel Course”.

VBA code to save workbook with WriteResPassword

The dialog box that Excel displays to ask for the WriteResPassword is slightly different than the one it uses when asking for the Password. Notice how it informs that the user who has saved the workbook reserved it and provides 2 options:

  • You can enter the password and Excel grants you write access.
  • Otherwise, you can open the workbook as read-only.

Password dialog for WriteResPassword generated by VBA

If I choose to open the workbook as read-only, Excel does precisely so. In that case, it warns in a few places that the workbook is read-only and changes aren’t saved.

Excel warns workbook is read-only

If you enter the wrong WriteResPassword, Excel reacts in the same way as it does when you enter the wrong Password (as shown above). In other words, it doesn’t open the workbook and displays the following message:

Incorrect WriteResPassword warning in Excel

Argument #5: ReadOnlyRecommended

The ReadOnlyRecommended argument provides you with a less strict way (when compared with the WriteResPassword above) to protect the Excel workbook you’re saving.

More precisely, if you set a particular workbook to be read-only recommended, Excel displays a message making such recommendation whenever the file is opened.

Excel message when opening read-only recommended workbook

Setting a workbook to be read-only recommended doesn’t actually protect or reserve the workbook in the same way as the Password or the WriteResPassword do. Any user can open a read-only recommended Excel workbook normally (not as read-only) by, for example:

  • Clicking “No” in the dialog box above.
  • Setting the IgnoreReadOnlyRecommended argument of the Workbooks.Open argument to True when opening the workbook using VBA.

To determine that an Excel workbook is read-only recommended, you simply set the ReadOnlyRecommended argument to True.

VBA code to save workbook with ReadOnlyRecommended

Argument #6: CreateBackup

The CreateBackup argument of the Workbook.SaveAs method allows you to determine whether a backup of the workbook being saved is created.

If you want to create a backup of the saved Excel workbook, set the CreateBackup argument to True.

VBA code saves workbook and creates backup

Argument #7: AccessMode

The AccessMode argument allows you to specify the access mode for the saved workbook. This argument can take the following 3 values:

  • 1: Stands for xlNoChange. In this case, the default access mode is used.
  • 2: Represents xlShared. In this case, the access mode is share list.
  • 3: Value for xlExclusive. In this scenario, access mode is exclusive mode.

The following screenshot shows the VBA code of the Save_Workbook_NewName macro with the AccessMode parameter set to xlNoChange:

VBA Sub procedure with Workbook.SaveAs and AccessMode

Argument #8: ConflictResolution

ConflictResolution applies when you’re working with shared workbooks. More precisely, this argument allows you to determine how conflicts (while saving the Excel workbook) are resolved.

You can set the ConflictResolution parameter to any of the following 3 values:

  • 1: Stands for xlUserResolution. In this case, Excel displays a dialog box asking the user to resolve the conflict. This is the default setting in case you omit the ConflictResolution argument.
  • 2: Represents xlLocalSessionChanges. If you choose this value, the changes made by the local user are accepted always.
  • 3: The value for xlOtherSessionChanges. This is the opposite from the above: the changes made by the local user are rejected always.

The following screenshot shows the code of the Save_Workbook_NewName macro with the ConflictResolution parameter set to the default xlUserResolution.

Example VBA code with ConflictResolution when saving

Argument #9: AddToMru

MRU stands for Most Recently Used. This makes reference to Excel’s list of most recently used files which, generally, you find on the Backstage View.

List of Most Recently Used workbooks in Excel

The AddToMru argument of the Workbook.Save method allows you to determine whether the saved workbook is added to this most recently used list.

If AddToMru is set to True, the Excel workbook is added to the list. The default value of AddToMru is, however, False.

In the following image, you can see the VBA code behind the sample Save_Workbook_NewName macro with AddToMru set to True:

AddToMru argument in VBA

As mentioned above, I’m not covering in detail the TextCodePage and TextVisualLayout arguments (arguments #10 and #11).

Argument #12: Local

The last argument of the Workbook.SaveAs method is Local. As implied by its name, Local refers to language and localization aspects of the saved workbook.

More precisely, the Local parameter allows you to determine whether the saved workbook is saved against the language of:

  • Excel, as generally determined from the control panel setting; or
  • VBA, which is usually US-English. The basic exception to this rule of VBA’s language being US-English occurs when the VBA project that executes the Workbook.SaveAs method is an internationalized XL5/95 VBA project. My guess is that you’re unlikely to work with such projects often.

To determine how Excel proceeds in connection with this topic, you can set the Local argument to True or False.

  • True: Saves the workbook against Excel’s language.
  • False: Saves the Excel workbook against VBA’s language.

In the following image, you can see the sample Save_Workbook_NewName with the Local parameter set to True:

Example VBA code wih Local argument

How To Save A Copy Of An Excel Workbook Using The Workbook.SaveCopyAs VBA Method

The Save and SaveAs methods explained above are the basic methods you’ll need to save Excel workbooks using VBA.

However, both of these methods save and modify the current open Excel workbook. You may encounter some situations where this isn’t the outcome you desire.

In other words, you’ll probably be in situations where you want a macro to simply:

  • Save a copy of the current Excel workbook, but…
  • Don’t actually modify the current file in the memory of the computer.

These type of situations are great for using the Workbook.SaveCopyAs VBA method. This method does precisely this. It takes the workbook and:

  • Saves a copy to a file.
  • Doesn’t modify it in memory.

The syntax of the SaveCopyAs method is, once again, relatively simple:

expression.SaveCopyAs(Filename)

Just as with the other methods explored in this Excel tutorial, “expression” represents a Workbook object. “Filename”, the only parameter of the SaveCopyAs method is the full file path, name and extension of the copy that you’re saving.

Since you’re likely to use this method on the active workbook most of the time, you’ll probably end up using the following syntax often:

ActiveWorkbook.SaveCopyAs(Filename)

Another commonly used alternative is to use the ThisWorkbook property instead of ActiveWorkbook. The main difference between ThisWorkbook and ActiveWorkbook is that:

  • ActiveWorkbook refers to the current active workbook.
  • ThisWorkbook refers to the workbook where the macro is actually stored.

Let’s take a look at an example of a macro that uses the Workbook.SaveCopyAs method to save a copy of the current active workbook:

The screenshot below shows a macro called “Save_Copy_Workbook”.

VBA code to save copy of workbook

This macro has a single (quite long) statement. This goes as follows:

ActiveWorkbook.SaveCopyAs Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name

Notice that the structure I use in the Save_Copy_Workbook macro follows the basic syntax of the Workbook.SaveCopyAs method explained above. However, let’s split the statement in 2 parts in order to understand better what’s going on, and what can this particular method do for you:

VBA code saving Excel workbook copy

Part #1: ActiveWorkbook.SaveCopyAs

This is the reference to the SaveCopyAs method. It follows the basic syntax explained above.

“ActiveWorkbook” makes reference to the Application.Workbook property. This property returns a Workbook object representing the current active workbook. This active workbook is the one which is manipulated by the SaveCopyAs method.

In other words, the statement simply tells Excel to proceed as follows:

  • Step #1: Take the current active workbook.
  • Step #2: Save a copy of the current active workbook, without actually modifying it in memory.

Part #2: Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name

This part of the statement specifies the only argument of the Workbook.SaveCopyAs method:

The Filename.

This particular file name for the copy is slightly long but, basically, is built by concatenating 5 items. You use the ampersand (&) operator to concatenate the different items.

Item #1: ActiveWorkbook.Path

This makes reference to the Workbook.Path property. The Path property returns the complete path to the relevant workbook.

In the case of the example above, “ActiveWorkbook.Path” is used to get the path to the current active workbook.

Let’s assume, for example, that the current active workbook (called “Book1”) is saved in the D drive. In this case the path is, simply “D:”.

This sample path (D:) isn’t very long or complicated. However, in practice, you’re more likely to work with longer and more complicated paths that you are to work with just the D drive.

Items #2 And #4: “Copy ” and ” “

This are, simply, text strings. The first string specifies that the first word in the file name is “Copy”. The second string adds a space ( ).

Item #3: Format(Now, “yy-mm-dd”)

This particular statement uses 2 VBA built-in functions, as follows:

  • Now returns today’s date and the current time. Alternatively, you can use the Date function, which returns the current date.
  • Format takes the date returned by Now and formats it according to the date format “yy-mm-dd”.

In other words, this part of the argument is responsible for returning the date in which the copy is saved in the format yy-mm-dd.

For example, if the date in which you save the copy of the workbook is November 30 of 2015, this item returns 15-11-30.

Item #5: ActiveWorkbook.Name

This item uses the Workbook.Name property to get the name of the workbook.

For example, if the name of the workbook is “Best Excel Tutorial”, Workbook.Name returns exactly that.

In order to make everything clear regarding the Workbook.SaveCopyAs method, let’s take a look at an example:

How To Save A Copy Of An Excel Workbook Using The Workbook.SaveCopyAs VBA Method: An Example

Let’s assume that the current active workbook is called “Best Excel Tutorial” and is saved in the D drive (D:). This is how the D drive looks like before I run the sample Save_Copy_Workbook macro:

D Drive before macro to save workbook copy

The following screenshot shows how the same drive looks after I run the macro. Notice how, now, there’s a new Excel workbook. This is the copy created by the Save_Copy_Workbook Sub procedure.

D Drive after saving copy of workbook using VBA

Let’s go back to the Filename argument of the SaveCopyAs method used within the Save_Copy_Workbook macro:

Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name

Notice how, each of the 5 items explained above expresses itself in practice once the macro is run:

  • Item #1: The copy is saved in the same folder as the original workbook, as given by the Workbook.Path property.
  • Items #2 and #4: The first word in the actual workbook name is Copy, as determined by the string “Copy”. Also, there is a space between the date (15-11-19) and the original workbook’s name (Best Excel Tutorial) as specified by ” “.
  • Item #3: The date in which the workbook is saved (November 19 of 2015 in the example above) is added to the name in the format yy-mm-dd (15-11-19).
  • Item #5: The name of the original workbook (Best Excel Tutorial) is added at the end of the copy’s name.

The following image shows this:

D Drive showing items of VBA code for workbook name

How To Name A Workbook Using The Application.GetSaveAsFilename Method

I introduced the Application.GetSaveAsFilename method above. This method is used by one of the sample macros (Save_Workbook_NewName) for purposes of opening the Save As dialog box and allow users to easily browse and enter the path, name and file extension of the saved Excel workbook.

The screenshot below shows the VBA code of the Save_Workbook_NewName macro. Notice the presence of the Application.GetSaveAsFilename method.

VBA code to name an Excel workbook

The Application.GetSaveAsFilename method doesn’t actually save a file. However, GetSaveAsFilename is a helpful method to use whenever you have a macro that needs to get a file name from the user in order to, among others, save a workbook.

GetSaveAsFilename is useful when the procedure needs to receive/know the name of the file to save. This gives the user the possibility of specifying the file’s path and filename.

As I explain below, you can use the Application.GetSaveAsFilename method precisely for these purposes.

The GetSaveAsFilename method has a few parameters that allow you to customize some of its characteristics. Let’s take a closer look at the method itself and its arguments, starting with:

The Application.GetSaveAsFilename Method: Purpose

The Application.GetSaveAsFilename method does 2 things:

  1. Displays the Save As dialog box.
  2. Gets the file name entered by the user in the Save As dialog box.

GetSaveAsFilename doesn’t save a workbook by itself. That’s why, for example, the Save_Workbook_NewName macro above includes uses the Workbook.SaveAs method to actually save the Excel workbook.

The Application.GetSaveAsFilename Method: Syntax

The full syntax of the Application.GetSaveAsFilename method is as follows:

expression.GetSaveAsFilename(InitialFilename, FileFilter, FilterIndex, Title, ButtonText)

“expression” is used to represent the Application object. You’re, therefore, likely to usually use the following basic syntax for this method:

Application.GetSaveAsFilename

This is the syntax used in the version of the Save_Workbook_NewName method shown above.

All of the 5 arguments of the GetSaveAsFilename method are optional. Let’s take a look at them:

The Application.GetSaveAsFilename Method: Arguments

The following table provides a basic description of the 5 parameters of the Application.GetSaveAsFilename method. I explain each of them more thoroughly below.

Position Name Description
1 InitialFilename Specifies a suggested/default file name.
2 FileFilter Determines file filtering criteria.
3 FilterIndex Determines the default file filter.
4 Title Determines the title of the (usually called) Save As dialog box.
5 ButtonText Applies only in the Mac platform.

Determines the text of the (normally called) Save As button.

There are quite a few similarities between the GetSaveAsFilename method and the GetOpenFilename method (which I describe here). In terms of their arguments, the main differences are as follows:

  • GetSaveAsFilename has the InitialFilename argument. GetOpenFilename doesn’t.
  • GetOpenFilename has the MultiSelect argument. GetSaveAsFilename doesn’t.

Both of these differences make sense. For example, MultiSelect allows you to determine whether a user can select multiple file names at the same time. This makes sense in the context of opening files. But not in the context of saving files with the GetSaveAsFilename method.

Let’s take a look at each of the parameters introduced above:

Argument #1: InitialFilename

The InitialFilename of the Application.GetSaveAsFilename method allows you to set a suggested file name. This suggested file name is the one that appears, by default, in the File name box of the Save As dialog.

Excel Save As dialog with suggested file name

The Save As dialog box displayed above is the result of running the following version of the Save_Workbook_NewName macro. Notice that the InitialFilename argument is added and the suggested name is “Best Excel Tutorial”, as displayed in the image above.

VBA code to name workbook showing InitialFileName

Argument #2: FileFilter

The FileFilter argument of the Application.GetSaveAsFilename method allows you to determine the criteria for file filtering within the Save As dialog box.

These file filtering criteria determine what appears in the Save as type drop-down list box of the Save As dialog box. If you omit the FileFilter argument, the default (as shown in the image below) is All Files.

Excel Save as dialog with file filters

This isn’t ideal because it may lead to the saved Excel workbook being of an unrecognizable file type if the user doesn’t enter the file extension when saving the file.

However, my guess is that you’ll be in situations where specifying the file filtering criteria is more convenient or, even, necessary. In order to be able to determine which file filters appear in the Save As dialog box, you’ll need to follow the 4 guidelines below.

Don’t worry if the guidelines don’t seem that clear at first. I show you a practical example of VBA code after making the introduction and basic description.

Guideline #1: Each Filter Consists Of A Pair Of Strings.

Each filter you specify when using the FileFilter argument is made up of 2 strings separated by a comma. This looks, roughly, as follows:

String1,String2

String1 and String2 have different structures and purposes. More precisely:

  • String1: Is a descriptive string. This string determines what actually appears in the Save as type drop-down box of the Save As dialog box.
  • String2: Is the MS-DOS wildcard file-type filter specification. In other words, this string determines how the files are actually filtered depending on their file format.

You don’t need to follow many guidelines regarding the way in which the first string (String1) is specified. However, you do need to follow a more specific syntax when specifying the second string (String2). Let’s take a look at it:

Guideline #2: Syntax To Specify The File-Type Filter.

The second string that you use to specify a file filter is itself composed of 3 elements which are, generally speaking, as follows:

  • Element #1: An asterisk (*), used as a wildcard.
  • Element #2: A dot (.).
  • Element #3: An indication of the file extension used to filter the files. This particular element is usually composed of (where appropriate) an asterisk (*), used as a wildcard, and/or (if appropriate), some text.

The most basic filter is all files, which in practice means that there’s no filter. To specify a file-type filter than includes all files using the syntax above, you’d type asterisk dot asterisk (*.*).

Other examples of file-type filter specifications following this syntax are the following:

  • *.txt for text files.
  • *.xla for add-ins.
  • *.xlsx for Excel workbooks.
  • *.xlsm for Macro-Enable Excel workbooks.
  • *.xls for Excel 97 to Excel 2003 workbooks.
  • *.csv for CSV files.

Knowing these first 2 guidelines is enough for you to start using the FileFilter argument. However, they only explain how to specify a single filter according to a single file type.

However, when working with FileFilter, you can actually specify:

  • Several different filters; as well as
  • Several different file types for each filter.

The next 2 guidelines show how you can do each of these:

Guideline #3: Syntax To Specify Several Filters.

You can create more than a single filter with the FileFilter argument. In order to so, use commas (,) to separate the filters. In other words, separate each of the pair of strings that constitute a filter from the other pair of strings by using commas (,).

This looks, roughly, as follows:

String1Filter1,String2Filter1,String1Filter2,String2Filter2

Guideline #4: Syntax To Specify Several File Types In A Single Filter.

If you need to filter according to several different data types, you can use several filters by using the syntax explained above.

Alternatively, you can specify several data types for a particular single filter. To do this, separate the MS-DOS wildcard expressions that you use with semicolons (;). This looks roughly as follows:

String1,String2.1;String2.2

Those are the 4 basic guidelines you need to bear in mind to start using the FileFilter argument. Let’s go back to the Save_Workbook_NewName macro and create some file filters:

The following screenshot shows (again) the VBA code behind Save_Workbook_NewName. Notice that the FileFilter argument has been inserted and its syntax follows all of the guidelines I explained above.

VBA code to name saved workbook with file filters

To make this clearer, let’s break the argument value into its different parts and highlight how it complies with all of the guidelines described above.

The complete argument is as follows:

“Excel Workbook,*.xlsx,Excel Macro-Enabled Workbook,*xlsm,Excel Templates,*.xltx;*.xltm”

Notice the following things:

  1. There are 3 filters. Each of the filters is separated from the other by commas (,).

    VBA code to name saved workbook with 3 filters

  2. Each filter is composed of 2 parts: a descriptive string and the relevant MS-DOS wildcard file-type filter specification. These 2 parts are separated by commas (,).

    VBA code to name saved workbook with parts of filters

  3. MS-DOS wildcard file-type filter specifications follow the syntax described above: (i) asterisk (*); (ii) dot (.); and (iii) file extension specification, without wildcard asterisks in this case.

    VBA code with file type filters

  4. The last filter uses 2 different file types. These file types are separated by a semicolon (;).

    VBA code to name saved workbook with 2 file-type filters

The following image shows how all of the above looks like in practice. Notice how, now, there are 3 different options within the Save as Type box of the Save As dialog box. These 3 filters are those created by the FileFilter argument of the Application.GetSaveAsFilename method.

Excel Save As dialog with filters created in VBA

Argument #3: FilterIndex

Notice how, in the image above, the default file filtering criteria is “Excel Workbook”. This is the first filter that was specified with the FileFilter argument.

You can, however, change the default file filtering criteria by using the FilterIndex argument. You do this by specifying the index number of the criteria you want to set as default.

As a consequence of the above, the FilterIndex argument can take any value between 1 (the first filter) and the number of filters you’ve specified with the FileFilter argument (3 in the example above).

If you set the FilterIndex value to a number higher than the amount of available filters (4 or higher in the case of the Save_Workbook_NewName macro), the first filter is used. In other words, the practical result of specifying an index number that is too high, is the same as that of omitting the FilterIndex parameter.

The following screenshot shows the code of the Save_Workbook_NewName macro with the FilterIndex parameter set to 2.

VBA code to name saved workbook with filter index

In the case of this macro, a FilterIndex value of 2 means that “Excel Macro-Enabled Workbook” is the new default filter.

Save As dialog with filter index from VBA

Argument #4: Title

The Title argument of the Application.GetSaveAsFilename method allows you to modify the title of the (usually called) Save As dialog box. If you omit the argument, the default title (Save As) is maintained.

The following image shows how this argument can be used to change the title of the Save As dialog box when executing the Save_Workbook_NewName macro. In this case, the Title argument is set to “VBA Save Excel Workbook”.

VBA code to name saved workbook and Title argument

When this macro is executed, the (previously called) Save As dialog looks as follows. Notice that the title has indeed changed to “VBA Save Excel Workbook”.

Excel Save As dialog with title from VBA

Argument #5: ButtonText

The ButtonText parameter is only applicable in the Mac platform. If you use this argument in Windows, it’s simply ignored.

For those cases where it is applicable, the ButtonText argument allows you to set the text that appears in the (usually known as) Save button.

Excel Save As dialog with Save button

Conclusion

Knowing how to save Excel workbooks using VBA is essential.

If you’ve read this Excel tutorial, you now know the basics of how to save workbooks using VBA. In fact, you’ve seen 3 different ways to achieve this:

  • Using the Workbook.Save method.
  • Using the Workbook.SaveAs method.
  • Using the Workbook.SaveCopyAs method.

Each of these cases is explained with the help of a real example of VBA code.

Additionally, in the last section of this blog post, I explained the Application.GetSaveAsFilename method. Even though this method doesn’t actually save a file by itself, it allows you to display the Save As dialog so that the users of your macro can easily specify the path and file name of the workbook they’re saving.

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!

vba save as

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

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.

Worksheets Object in Excel VBA - file name in 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).

Workbook Object in VBA - ThisWorkbook

‘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:

Workbook Object in VBA - Warning when saving Workbook for the first time

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.

Workbook Object in VBA - Runtime 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:

  1. Go to the Developer tab.Using Workbooks in Excel VBA - Developer Tab in ribbon
  2. Click on the Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. 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.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.Using Workbooks in Excel VBA - inserting module
  5. Copy and paste the code in the module window.Using Workbooks in Excel VBA - inserting module

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).

VBA Save Workbook

Excel VBA Save Workbook

In this article, we will see an outline on Excel VBA Save Workbook. It is very easy to create a macro for saving a Microsoft file. The code ranges from 1 line to 10 lines of code. And it is all up to us and our application which code we need to use. Although, a file can be saved just by pressing the shortcut key Ctrl+S. Or else click over the Save Icon which we can easily get at the top of the Excel file. That location is called the Title bar. And this is a location at the extreme left top corner on it. When the process of saving a file is so easy then why we need an extra step to make it happen. Reason can be different for different people, but major justification is when a huge data set in which we want to automate that fully or partially, saving the file after everything is done, may freeze the file. So it is better to save the file once the complete code is run, the process is done. By this, we can save extra time saving the huge data file in additional process and avoid file getting hung or crash. We will be seeing all the different types of code in upcoming examples.

How to Save Workbook in Excel VBA?

The following examples will teach us how to Save the Workbook in Excel by using the VBA Code.

You can download this VBA Save Workbook Excel Template here – VBA Save Workbook Excel Template

VBA Save Workbook – Example #1

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Now write the subprocedure for the VBA Save workbook or we can choose any name to define it.

Code:

Sub VBA_SaveWorkBook()

End Sub

VBA Save Workbook Example1-1

Step 3: Now to select the current workbook, use Active workbook as shown below followed by a dot.

Code:

Sub VBA_SaveWorkBook()

ActiveWorkbook.

End Sub

Active workbook Example1-2

Step 4: Search Save function from the list.

Code:

Sub VBA_SaveWorkBook()

ActiveWorkbook.Save

End Sub

Save function Example1-3

Now run the code by clicking on the Play button located below the menu bar.

Just to see whether the file is getting saved or not, keep VBA and Excel window parallel to each other. We will see, the file is now saved by showing the quick process of process.

VBA Save Workbook – Example #2

There is another way to save a workbook with one line of code. For this, we can use the same code which we have seen in example-1. For this, follow the steps below:

Step 1: Now in the same code, we will replace Active Workbook with ThisWorkBook. This is another way to select the current workbook which is selected. Now again run the code. We will see the file is save just by showing the waiting blue circle in quick seconds.

Code:

Sub VBA_SaveWorkBook2()

ThisWorkbook.Save

End Sub

VBA Save Workbook Example2-2

Now moving to a little complex set of code but still also an easy way to save any workbook. For this, follow the steps below:

Step 2: Write the subprocedure for VBA Save Book as shown below.

Code:

Sub VBA_SaveWorkBook3()

End Sub

VBA Save Workbook Example3-1

Step 3: In this example, we will be using the For Each-Next loop to perform saving workbooks. Now define a variable using DIM as type Workbook.

Code:

Sub VBA_SaveWorkBook3()

Dim Workbook As Workbook

End Sub

DIM Example3-2

Step 4: Now we will open a For loop write the condition for each defined variable Workbook activate the applications in the workbook.

Code:

Sub VBA_SaveWorkBook3()

Dim Workbook As Workbook
For Each Workbook In Application.Workbooks

End Sub

For loop Example3-3

Step 5: Now use Workbook along with function Save as shown below.

Code:

Sub VBA_SaveWorkBook3()

Dim Workbook As Workbook
For Each Workbook In Application.Workbooks
Workbook.Save

End Sub

VBA Save Workbook Example3-4

Step 6: Close the loop by Next and using defined variable Workbook here as well.

Code:

Sub VBA_SaveWorkBook3()

Dim Workbook As Workbook
For Each Workbook In Application.Workbooks
Workbook.Save
Next Workbook

End Sub

Loop by Next Example3-5

We can compile the complete code and run. We will notice again, quickly the code has saved the file again.

VBA Save Workbook – Example #3

There is another easy way to save the workbook using VBA code. For this, follow the below steps:

Step 1: Write the subprocedure for VBA Save Workbook.

Code:

Sub VBA_SaveWorkBook4()

End Sub

VBA Save Workbook Example4-1

Step 2: Here also, we will need a variable which we used in the previous example.

Code:

Sub VBA_SaveWorkBook4()

Dim Workbook As Workbook

End Sub

VBA Save Workbook Example4-2

Step 3: Now use Set object along with a defined variable.

Code:

Sub VBA_SaveWorkBook4()

Dim Workbook As Workbook
Set Workbook =

End Sub

VBA Save Workbook Example4-3

Step 4: Then use Workbooks function and in brackets insert the name of the workbook which we want to save. Here the name of the workbook is “VBA Save Workbook” with extension. This should be the name of the file in which we are writing the code.

Code:

Sub VBA_SaveWorkBook4()

Dim Workbook As Workbook
Set Workbook = Workbooks("VBA Save Workbook.xlsm")

End Sub

VBA Save Workbook Example4-4

Step 5: Now use a Workbook variable with Save.

Code:

Sub VBA_SaveWorkBook4()

Dim Workbook As Workbook
Set Workbook = Workbooks("VBA Save Workbook.xlsm")
Workbook.Save

End Sub

VBA Save Workbook Example4-5

Once done, run the code. We will notice the small waiting circle will appear for a few moments and the file is got saved.

Pros & Cons of VBA Save Workbook

  • It is the easiest code in VBA to write.
  • All the examples shown in the article are easy to implement.
  • Not useful if used in a small set of code and for small data sets.

Things to Remember

  • It is advised to use VBA Save Workbook code, once we complete the rest of the line of code or at the end of the entire code line.
  • VBA Save Workbook is not limited to the examples which we have seen in the above article.
  • Quote the name of the file in inverted commas always.
  • Use macro enable excel format extension. It is the only version of MS Excel where we can save our VBA Code.
  • Not advised to use this VBA Save Workbook in a small code structure. It will not give any major improvement in the selection of work.

Recommended Articles

This is a guide to VBA Save Workbook. Here we discuss how to Save Workbook in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Month
  2. VBA On Error GoTo 0
  3. VBA On Error Resume Next
  4. VBA AND

“We are drowning in information but starved for knowledge.” – John Naisbitt

This post provides a complete guide to using the VBA Workbook.

If you want to use VBA to Open a Workbook then check out Open Workbook

If you want to use VBA to create a new workbook go to Create New Workbook

For all other VBA Workbook tasks, check out the quick guide below.

A Quick Guide to the VBA Workbook

The following table provides a quick how-to guide on the main VBA workbook tasks

Task How to
Access open workbook using name Workbooks(«Example.xlsx»)
Access open workbook (the one opened first) Workbooks(1)
Access open workbook (the one opened last) Workbooks(Workbooks.Count)
Access the active workbook ActiveWorkbook
Access workbook containing VBA code ThisWorkbook
Declare a workbook variable Dim wk As Workbook
Assign a workbook variable Set wk = Workbooks(«Example.xlsx»)
Set wk = ThisWorkbook
Set wk = Workbooks(1)
Activate workbook wk.Activate
Close workbook without saving wk.Close SaveChanges:=False
Close workbook and save wk.Close SaveChanges:=True
Create new workbook Set wk = Workbooks.Add
Open workbook Set wk =Workbooks.Open («C:DocsExample.xlsx»)
Open workbook as read only Set wk = Workbooks.Open («C:DocsExample.xlsx», ReadOnly:=True)
Check Workbook exists If Dir(«C:Docsbook1.xlsx») = «» Then
MsgBox «File does not exist.»
EndIf
Check Workbook is open See Check Workbook Open section below
List all open workbooks For Each wk In Application.Workbooks
    Debug.Print wk.FullName
Next wk
Open workbook with the File Dialog See File Dialog section below function below
Save workbook wk.Save
Save workbook copy wk.SaveCopyAs «C:Copy.xlsm»
Copy workbook if closed FileCopy «C:file1.xlsx»,«C:Copy.xlsx»
SaveAs workbook wk.SaveAs «Backup.xlsx»

VBA Workbook Webinar

If you are a member of the website, click on the image below to access the webinar.

(Note: Website members have access to the full webinar archive.)

vba workbook video

Getting Started with the VBA Workbook

We can access any open workbook using the code Workbooks(“Example.xlsm). Simply replace Example.xlsm with the name of the workbook you wish to use.

 
The following example shows you how to write to a cell on a worksheet. You will notice we had to specify the workbook, worksheet and range of cells.

' https://excelmacromastery.com/
Public Sub WriteToA1()

    ' Writes 100 to cell A1 of worksheet "Sheet1" in MyVBA.xlsm
Workbooks("MyVBA.xlsm").Worksheets("Sheet1").Range("A1") = 100

End Sub

 
This example may look a little be confusing to a new user but it is actually quite simple.

The first part up to the decimal point is the Workbook, the second part is the Worksheet and the third is the Range. Here are some more examples of writing to a cell

' https://excelmacromastery.com/
Public Sub WriteToMulti()

' Writes 100 to cell A1 of worksheet "Sheet1" in MyVBA.xlsm
Workbooks("MyVBA.xlsm").Worksheets("Sheet1").Range("A1") = 100

' Writes "John" to cell B1 of worksheet "Sheet1" in MyVBA.xlsm
Workbooks("MyVBA.xlsm").Worksheets("Sheet1").Range("B1") = "John"

' Writes 100 to cell A1 of worksheet "Accounts" in MyVBA.xlsm
Workbooks("MyVBA.xlsm").Worksheets("Accounts").Range("A1") = 100

' Writes the date to cell D3 of worksheet "Sheet2" in Book.xlsc
Workbooks("Book.xlsx").Worksheets("Sheet2").Range("D3") = "112016"

End Sub

 
You can see the simple pattern here. You can write to any cell in any worksheet from any workbook. It is just a matter of changing the workbook name, worksheet name and the range to suit your needs.

Take a look at the workbook part

Workbooks("Example.xlsx")

 
The Workbooks keyword refers to a collection of all open workbooks. Supplying the workbook name to the collection gives us access to that workbook. When we have the object we can use it to perform tasks with the workbook.

Troubleshooting the Workbooks Collection

When you use the Workbooks collection to access a workbook, you may get the error message:

Run-time Error 9: Subscript out of Range.

This means that VBA cannot find the workbook you passed as a parameter.

This can happen for the following reasons

  1. The workbook is currently closed.
  2. You spelled the name wrong.
  3. You created e new workbook (e.g. Book1) and tried to access it using Workbooks(“Book1.xlsx”). It’s name is not Book1.xlsx until it is saved for the first time.
  4. (Excel 2007/2010 only) If you are running two instances of Excel then Workbooks() only refers to to the workbooks open in the current Excel instance.
  5. You passed a number as Index and it is greater than the number of workbooks open e.g. you used Workbooks(3) and only two workbooks are open.

 
If you cannot resolve the error then use either of the functions in the section Finding all open Workbooks. These will print the names of all open workbooks to the Immediate Window(Ctrl + G).

Examples of Using the VBA Workbook

The following examples show what you can do with the workbook.

Note: To try this example create two open workbooks called Test1.xlsx and Test2.xlsx.

' https://excelmacromastery.com/
Public Sub WorkbookProperties()

    ' Prints the number of open workbooks
    Debug.Print Workbooks.Count

    ' Prints the full workbook name
    Debug.Print Workbooks("Test1.xlsx").FullName

    ' Displays the full workbook name in a message dialog
    MsgBox Workbooks("Test1.xlsx").FullName

    ' Prints the number of worksheets in Test2.xlsx
    Debug.Print Workbooks("Test2.xlsx").Worksheets.Count

    ' Prints the name of currently active sheet of Test2.xlsx
    Debug.Print Workbooks("Test2.xlsx").ActiveSheet.Name

    ' Closes workbook called Test1.xlsx
    Workbooks("Test1.xlsx").Close

    ' Closes workbook Test2.xlsx and saves changes
    Workbooks("Test2.xlsx").Close SaveChanges:=True

End Sub

 
 Note: In the code examples I use Debug.Print a lot. This function prints values to the Immediate  Window. To view this window select View->Immediate Window from the menu( Shortcut is Ctrl + G)

 
ImmediateWindow

 
ImmediateSampeText

Accessing the VBA Workbook by Index

You can also use an Index number with Workbooks(). The index refers to the order the Workbook was open or created.

 
Workbooks(1) refers to the workbook that was opened first. Workbooks(2) refers to the workbook that was opened second and so on.

' First workbook that was opened
Debug.Print Workbooks(1).Name

' Third workbook that was opened
Debug.Print Workbooks(3).Name

' The last workbook that was opened
Debug.Print Workbooks(Workbooks.Count).Name

 
In this example, we used Workbooks.Count. This is the number of workbooks that are currently in the Workbooks collection. That is, the number of workbooks currently open. So using it as the Index gives us the last workbook that was opened

Using the index is not really useful unless you really need to know the order. For this reason, you should avoid using it. You should use the workbook name with Workbooks() instead.

Finding all Open Workbooks

Sometimes you may want to access all the workbooks that are open. In other words, all the items in the Workbooks() collection.

You can do this using the For Each loop.

' https://excelmacromastery.com/
Public Sub PrintWrkFileName()

    ' Prints out the full filename of all open workbooks
    Dim wrk As Workbook
    For Each wrk In Workbooks
        Debug.Print wrk.FullName
    Next wrk

End Sub

 
You can also use the standard For loop to access all the open workbooks

' https://excelmacromastery.com/
Public Sub PrintWrkFileNameIdx()

    ' Prints out the full filename of all open workbooks
    Dim i As Long
    For i = 1 To Workbooks.Count
        Debug.Print Workbooks(i).FullName
    Next i

End Sub

 
For accessing workbooks, either of these Loops is fine. The standard For loop is useful if you want to use a different order or you need to use a counter.

Note: Both examples read in the order of the first opened to the last opened. If you want to read in reverse order(last to first) you can do this

' https://excelmacromastery.com/
Public Sub PrintWrkFileNameIdxRev()

    ' Prints out the full filename of all open workbooks
    ' in reverse order.
    Dim i As Long
    For i = Workbooks.Count To 1 Step -1
        Debug.Print Workbooks(i).FullName
    Next i

End Sub

Open Workbook

So far we have dealt with workbooks that are already open. Of course, having to manually open a workbook before running a Macro, defeats the purpose of automating tasks. The Open Workbook task should be performed by VBA.

The following VBA code opens the workbook “Book1.xlsm” in the “C:Docs” folder

' https://excelmacromastery.com/
Public Sub OpenWrk()

    ' Open the workbook and print the number of sheets it contains
    Workbooks.Open ("C:DocsBook1.xlsm")

    Debug.Print Workbooks("Book1.xlsm").Worksheets.Count

    ' Close the workbook without saving
    Workbooks("Book1.xlsm").Close saveChanges:=False

End Sub

 
It is a good idea to check a workbook actually exists before you try to open it. This will prevent you getting errors. The Dir function allows you to easily do this .

' https://excelmacromastery.com/
Public Sub OpenWrkDir()

    If Dir("C:DocsBook1.xlsm") = "" Then
        ' File does not exist - inform user
        MsgBox "Could not open the workbook. Please check it exists"
    Else
        ' open workbook and do something with it
        Workbooks.Open("C:DocsBook1.xlsm")
    End If

End Sub

Check For Open Workbook

If you are opening a workbook as Read-Only, it doesn’t matter if it is already open. However, if you’re going to update data in a workbook then it is a good idea to check if it is already open.

The function below can be used to check if the workbook is currently open. If not, then it will open the workbook. In either case you will end up with the workbook opened.

(The code below is taken from this StackOverFlow entry.)

' https://excelmacromastery.com/
Function GetWorkbook(ByVal sFullFilename As String) As Workbook
    
    Dim sFilename As String
    sFilename = Dir(sFullFilename)
    
    On Error Resume Next
    Dim wk As Workbook
    Set wk = Workbooks(sFilename)
    
    If wk Is Nothing Then
        Set wk = Workbooks.Open(sFullFilename)
    End If
    
    On Error Goto 0
    Set GetWorkbook = wk
    
End Function

You can use this function like this

' https://excelmacromastery.com/
Sub ExampleOpenWorkbook()

    Dim sFilename As String
    sFilename = "C:DocsBook2.xlsx"

    Dim wk As Workbook
    Set wk = GetWorkbook(sFilename)
    
End Sub

This code is fine is most situations. However, if the workbook could be currently open in read-only mode or could be currently opened by another user then you may want to use a slightly different approach.

An easy way to deal this with this scenario is to insist that the file must be closed for the application to run successfully. You can use the function below to simply check is the file already open and if so inform the user that it must be closed first.

(The code below is also taken from this StackOverFlow entry)

' https://excelmacromastery.com/
' Function to check if workbook is already open
Function IsWorkBookOpen(strBookName As String) As Boolean
    
    Dim oBk As Workbook
    
    On Error Resume Next
    Set oBk = Workbooks(strBookName)
    On Error GoTo 0
    
    If Not oBk Is Nothing Then
        IsWorkBookOpen = True
    End If
    
End Function

 
An example of using this function is shown below. In this case, if the workbook is already open then you inform the user that is must be closed for the macro to proceed.

' https://excelmacromastery.com/
Sub ExampleUse()

    Dim sFilename As String
    sFilename = "C:tempwritedata.xlsx"

    If IsWorkBookOpen(Dir(sFilename)) = True Then
        MsgBox "File is already open. Please close file and run macro again."
        Exit Sub
    End If
    
    ' Write to workbook here
    
End Sub

 
If you need to check if the workbook is open in another instance of Excel you can use the ReadOnly attribute of the workbook. It will be set to true if it is open in another instance.

Close Workbook

To Close a Workbook in Excel VBA is very simple. You simply call the Close method of the workbook.

wk.Close

 
Normally when you close a workbook in VBA, you don’t want to see messages from Excel asking if you want to save the file.

You can specify whether to save the workbook or not and then the Excel messages will not appear.

' Don't save changes
wk.Close SaveChanges:= False

' Do save changes
wk.Close SaveChanges:= True

 
Obviously, you cannot save changes to a workbook that is currently open as read-only.

Save Workbook

We have just seen that you can save a workbook when you close it. If you want to save it any other stage you can simply use the Save method

wk.Save

 
You can also use the SaveAs method

wk.SaveAs "C:Backupsaccounts.xlsx"

 
The Workbook SaveAs method comes with twelve parameters which allow you to add a password, set the file as read-only and so on. You can see the details here.

 
You can also use VBA to save the workbook as a copy using SaveCopyAs

wk.SaveCopyAs "C:DocsCopy.xlsm"

Copy Workbook

If the workbook is open you can use the two methods in the above section to create a copy i.e. SaveAs and SaveCopyAs.

 
 
If you want to copy a workbook without opening it then you can use FileCopy as the following example demonstrates

Public Sub CopyWorkbook()
    FileCopy "C:DocsDocs.xlsm", "C:DocsExample_Copy.xlsm"
End Sub

Using the File Dialog To Open a Workbook

The previous section shows you how to open a workbook with a given name. Sometimes you may want the user to select the workbook. You can easily use the Windows File Dialog shown here.

FileDialog VBA Workbook

The Windows File Dialog

 
 
The FileDialog is configurable and you can use it to

  1. Select a file.
  2. Select a folder.
  3. Open a file.
  4. “Save As” a file.

 
If you just want the user to select the file you can use the GetOpenFilename function.

 
The following function opens a workbook using the File Dialog. The function returns the full file name if a file was selected. If the user cancels it displays a message and returns an empty string.

' https://excelmacromastery.com/
Public Function UserSelectWorkbook() As String

    On Error Goto ErrorHandler

    Dim sWorkbookName As String

    Dim FD As FileDialog
    Set FD = Application.FileDialog(msoFileDialogFilePicker)

    ' Open the file dialog
    With FD
        ' Set Dialog Title
        .Title = "Please Select File"

        ' Add filter
        .Filters.Add "Excel Files", "*.xls;*.xlsx;*.xlsm"

        ' Allow selection of one file only
        .AllowMultiSelect = False

        ' Display dialog
        .Show

        If .SelectedItems.Count > 0 Then
            UserSelectWorkbook = .SelectedItems(1)
        Else
            MsgBox "Selecting a file has been cancelled. "
            UserSelectWorkbook = ""
        End If
    End With

    ' Clean up
    Set FD = Nothing
Done:
    Exit Function
ErrorHandler:
    MsgBox "Error: " + Err.Description
End Function

 
When you call this function you have to check for the user cancelling the dialog. The following example shows you how to easily call the UserSelectWorkbook function and handle the case of the user cancelling

' https://excelmacromastery.com/
Public Sub TestUserSelect()

    Dim userBook As Workbook, sFilename As String

    ' Call the UserSelectworkbook function
    sFilename = UserSelectWorkbook()

    ' If the filename returns is blank the user cancelled
    If sFilename <> "" Then
        ' Open workbook and do something with it
        Set userBook = Workbooks.Open(sFilename)
    End If

End Sub

 
You can customise the dialog by changing the Title, Filters and AllowMultiSelect in the UserSelectWorkbook function.

Using ThisWorkbook

There is an easier way to access the current workbook than using Workbooks(). You can use the keyword ThisWorkbook. It refers to the current workbook i.e. the workbook that contains the VBA code.

If our code is in a workbook call MyVBA.xlsm then ThisWorkbook and Workbooks(“MyVBA.xlsm”) refer to the same workbook.

 
Using ThisWorkbook is more useful than using Workbooks(). With ThisWorkbook we do not need to worry about the name of the file. This gives us two advantages:

  1. Changing the file name will not affect the code
  2. Copying the code to another workbook will not require a code change

 
These may seem like very small advantages. The reality is your filenames will change all the time. Using ThisWorkbook  means your code will still work fine.

 
The following example shows two lines of code. One using ThisWorkbook  and one using Workbooks(). The one using Workbooks will no longer work if the name of MyVBA.xlsm changes.

' https://excelmacromastery.com/
Public Sub WriteToCellUsingThis()

    ' Both lines do the same thing.
    Debug.Print ThisWorkbook.FullName
    Debug.Print Workbooks("MyVBA.xlsm").FullName

End Sub

Using the ActiveWorkbook

ActiveWorkbook refers to the workbook that is currently active. This is the one that the user last clicked on.

This can seem useful at first. The problem is that any workbook can become active by a simple mouse click. This means you could easily write data to the wrong workbook.

Using ActiveWorkbook also makes the code hard to read. It may not be obvious from the code which workbook should be the active one.

I hope I made it clear that you should avoid using ActiveWorkbook unless you really have to. If you must then be very careful.

Examples of the Accessing the Workbook

We’ve looked at all the ways of accessing a workbook. The following code shows examples of these ways

' https://excelmacromastery.com/
Public Sub WorkbooksUse()

    ' This is a workbook that is already open and called MyVBA.xlsm
    Debug.Print Workbooks("MyVBA.xlsm").FullName

    ' The workbook that contains this code
    Debug.Print ThisWorkbook.FullName

    ' The open workbook that was opened first
    Debug.Print Workbooks(1).FullName

    ' The open workbook that was opened last
    Debug.Print Workbooks(Workbooks.Count).FullName

    ' The workbook that is the currently active one
    Debug.Print ActiveWorkbook.FullName

    ' No workbook mentioned - the active one will be used
    Debug.Print Worksheets("Sheet1").Name

    ' A closed workbook called Book1.xlsm in folder C:Docs
    Workbooks.Open ("C:DocsBook1.xlsm")
    Debug.Print Workbooks("Book1.xlsm").FullName
    Workbooks("Book1.xlsm").Close

End Sub

Declaring a VBA Workbook variable

The reason for declaring a workbook variable is to make your code easier to read and understand. It is easier to see the advantage of using an example

' https://excelmacromastery.com/
Public Sub OpenWrkObjects()

    Dim wrk As Workbook
    Set wrk = Workbooks.Open("C:DocsBook1.xlsm")

    ' Print number of sheets in each book
    Debug.Print wrk.Worksheets.Count
    Debug.Print wrk.Name

    wrk.Close

End Sub

 
You can set a workbook variable with any of the access methods we have seen.

The following shows you the same code without a workbook variable

' https://excelmacromastery.com/
Public Sub OpenWrkNoObjects()

   Workbooks.Open ("C:DocsBook1.xlsm")

   Debug.Print Workbooks("Book2.xlsm").Worksheets.Count
   Debug.Print Workbooks("Book2.xlsm").Name

    Workbooks("Book2.xlsm").Close

End Sub

 
In these examples the difference is not major. However, when you have a lot of code, using a variable is useful particularly for worksheet and ranges where the names tend to be long e.g. thisWorkbook.Worksheets(“Sheet1”).Range(“A1”).

You can name the workbook variable to be something like wrkRead or wrkWrite. Then at a glance you can see what this workbook is being used for.

Create New Workbook

To create a new workbook you use the Workbooks Add function. This function creates a new blank workbook. It is the same as selecting New Workbook from the Excel File menu.

 
When you create a new workbook you will generally want to save it. The following code shows you how to do this.

' https://excelmacromastery.com/
Public Sub AddWordbook()

    Dim wrk As Workbook
    Set wrk = Workbooks.Add

    ' Save as xlsx. This is the default.
    wrk.SaveAs "C:TempExample.xlsx"

    ' Save as a Macro enabled workbook
    wrk.SaveAs "C:TempExample.xlsm", xlOpenXMLWorkbookMacroEnabled

End Sub

 
When you create a new workbook it normally contains three sheets. This is determined by the property Application.SheetsInNewWorkbook.

 
If you want to have a different number of sheets in a new workbook then you change this property before you create the new workbook. The following example shows you how to create a new workbook with seven sheets.

' https://excelmacromastery.com/
Public Sub AddWordbookMultiSheets()

    ' Store SheetsInNewWorkbook value so we can reset it later
    Dim sheetCnt As Long
    sheetCnt = Application.SheetsInNewWorkbook

    ' Set sheets in a new workbook to be 7
    Application.SheetsInNewWorkbook = 7

    ' Workbook will be created with 7 sheets
    Dim wrk As Workbook
    Set wrk = Workbooks.Add

    ' Display sheet count
    Debug.Print "number of sheets: " & CStr(wrk.Worksheets.Count)

    ' Reset to original value
    Application.SheetsInNewWorkbook = sheetCnt

End Sub

The With keyword and the Workbook

The With keyword makes reading and writing VBA code easier. Using With means you only need to mention the item once. With  is used with Objects. These are items such as Workbooks, Worksheets and Ranges.

 
The following example has two Subs. The first is similar to code we have seen so far. The second uses the With keyword. You can see the code is much clearer in the second Sub. The keywords End With mark the finish of a section code using With.

' https://excelmacromastery.com/
' Not using the With keyword
Public Sub NoUsingWith()

   Debug.Print Workbooks("Book2.xlsm").Worksheets.Count
   Debug.Print Workbooks("Book2.xlsm").Name
   Debug.Print Workbooks("Book2.xlsm").Worksheets(1).Range("A1")
   Workbooks("Book2.xlsm").Close

End Sub

' Using With makes the code easier to read
Public Sub UsingWith()

    With Workbooks("Book2.xlsm")
        Debug.Print .Worksheets.Count
        Debug.Print .Name
        Debug.Print .Worksheets(1).Range("A1")
        .Close
    End With

End Sub

Summary

The following is a brief summary of the main points of this post

  1. To get the workbook containing the code use ThisWorkbook.
  2. To get any open workbook use Workbooks(“Example.xlsx”).
  3. To open a workbook use Set Wrk = Workbooks.Open(“C:FolderExample.xlsx”).
  4. Allow the user to select a file using the UserSelectWorkbook function provided above.
  5. To create a copy of an open workbook use the SaveAs property with a filename.
  6. To create a copy of a workbook without opening use the FileCopy function.
  7. To make your code easier to read and write use the With keyword.
  8. Another way to make your code clear is to use a Workbook variables
  9. To run through all open Workbooks use For Each wk in Workbooks where wk is a workbook variable.
  10. Try to avoid using ActiveWorkbook and Workbooks(Index) as their reference to a workbook is temporary.

You can see a quick guide to the topic at the top of this post

Conclusion

This was an in-depth post about a very important element of VBA – the Workbook.  I hope you found it beneficial. Excel is great at providing many ways to perform similar actions but the downside is it can lead to confusion at times.

To get the most benefit from this post I recommend you try out the examples. Create some workbooks and play around with the code. Make changes to the code and see how the changes affect the outcome. Practice is the best way to learn VBA.

If you found this post useful then feel free to share it with others using the bar at the side.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Skip to content

Save Workbook Using Excel VBA to Specific Folder

Home » Excel VBA » Save Workbook Using Excel VBA to Specific Folder

  • SaveAs dialogbox

VBA save as Workbook Excel Macro code helps Save file to a specific Folder, its is a common task in automation process. Once you are done with actual calculations or task, at end of the procedure we generally call a procedure to export or Save the Output File to a Specific Folder or common drive. Or in other case you may not have the permissions to Save the File in a location, so that you can use SaveAs Option to store the revised or updated file.

VBA save as Workbook – Solution(s):

Save Workbook Using Excel VBA to Specific Folder You can use SaveAs method to Save the File to a specific location. You can Save with the same File Name and Location. Or you can use different File Name and Location to Save the File. You can also set to an object and Save the File.

In other method, you use Save Dialog Box. So that user can choose a specific folder to save the Excel File.

Save Workbook to Specific Folder – Example Cases:

  • Save Workbook to Specific Folder
  • Set to an Object and Save it
  • Save Workbook to Specific Folder using Save Dialog Box
  • Save Workbook in the same location of the Macro (this) Workbook
  • Save the Workbook
  • Download: Example Macro Workbook
Save a Workbook to a Specific Folder

The following example show you how to save an Excel Workbook in Specific folder using SaveAs method:

Sub ExampleToSaveWorkbook()

Workbooks.Add
'Saving the Workbook
ActiveWorkbook.SaveAs "C:WorkbookName.xls"
'OR
'ActiveWorkbook.SaveAs Filename:="C:WorkbookName1.xls"

End Sub
Set to an Object and Save it

Set to an Object and Save it, so that it is easy to refer to your workbook to do further tasks. If you are dealing with more than one workbook, you will need this method to access a specific Excel Workbook.

Sub ExampleToSaveWorkbookSet()

Dim wkb As Workbook
'Adding New Workbook
Set wkb = Workbooks.Add
'Saving the Workbook
wkb.SaveAs "C:WorkbookName.xls"
'OR
'wkb.SaveAs Filename:="C:WorkbookName1.xls"

End Sub
Save Workbook to Specific Folder using Save Dialog Box

You can Save the Workbook to Specific Folder by showing the Save Dialog Box to user. So that user can choose desired location to save the file.

SaveAs dialogbox

Sub sbSaveExcelDialog()

Dim IntialName As String
Dim sFileSaveName As Variant
IntialName = "Sample Output"
sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, fileFilter:="Excel Files (*.xlsm), *.xlsm")

If sFileSaveName <> False Then
    ActiveWorkbook.SaveAs sFileSaveName
End If

End Sub

Save Workbook in the same location of the Macro (this) Workbook

You can save the workbook in the same directory of the macro workbook using ThisWorkbook.Path property.

Sub ExampleToSaveWithSamePathDifferentName()
Dim sFilename As String
sFilename = "WorkbookName.xls" 'You can give a nem to save

Workbooks.Add
'Saving the Workbook
ActiveWorkbook.SaveAs ThisWorkbook.Path & "" & sFilename

End Sub

Save the Workbook

You can simply save the file without changing its file name or path name using Save method.

Sub ExampleToSaveWithSameNameandPath()

'Saving the Workbook
ActiveWorkbook.Save

End Sub
Example Files

You can download the example file and explore it.
ANALYSISTABS – Save Workbook

Overwrite an Existing Workbook using VBA

While Saving the existing workbook or a new excel file with existing name, Excel will prompt a warning message. It will interrupt the procedure and ask user to press yes or no for overwriting a file.

Overwrite an Existing Workbook using VBA – Solution:

Overwrite an Existing Workbook in Excel VBA
You can avoid this by disabling the alerts temporarily and save the workbook with the same name by setting the Application.DisplayAlerts=False property. Once you are done with the task, you should enable the application alerts by setting the property TRUE.

Overwrite an Existing Workbook using VBA – An Example

The following example will show you, how to overwrite a file by disabling the application alerts.

Code:
sub procedure to over write an excel file
Sub ExampleToOverWriteExistingWorkbook()
'Declaration: Declaring the variable
Dim wkb As Workbook

'Adding New Workbook using Workbook.Add method and setting to wkb Object
Set wkb = Workbooks.Add

'Saving the Workbook

'Desable the application alerts before svaing the file
Application.DisplayAlerts = False

'Now save the file
wkb.SaveAs "C:WorkbookName.xls" ' change to existng file name
'OR
'wkb.SaveAs Filename:="C:WorkbookName1.xls"</span>

'Eanbling the Application Aletrts after saving the file
Application.DisplayAlerts = True

End Sub
Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Insert a Module for Insert Menu
  4. Copy the above code and Paste in the code window
  5. Save the file as macro enabled workbook
  6. Press F5 to execute itit
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • VBA save as Workbook – Solution(s):
  • Save Workbook to Specific Folder – Example Cases:
    • Overwrite an Existing Workbook using VBA
    • Overwrite an Existing Workbook using VBA – Solution:

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

28 Comments

  1. Katharina
    February 3, 2014 at 9:22 AM — Reply

    Your means of describing all in this paragraph is really good,
    every one be able to easily understand it, Thanks a
    lot.

  2. PNRao
    February 3, 2014 at 9:54 AM — Reply
  3. Rob
    October 15, 2014 at 5:30 AM — Reply

    Having trouble using the below code. Any ideas?
    SaveFile = Application.GetSaveAsFilename( _
    FileFilter:=”Excel Files (*.xlsx), *.xlsx”)
    ActiveWorkbook.SaveAs SaveFile

    After the file is saved it appears as an Excel file in the indicated location, but when you try to open it a dialogue box says: “Excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.”

  4. PNRao
    October 18, 2014 at 1:57 PM — Reply

    Hi Rob,
    I found no issues in your code, you may be using Excel 2003. If your Excel is not 2007 or higher, you can change the “Excel Files (*.xlsx), *.xlsx” as “Excel Files (*.xls), *.xls”

    i.e; xls, instead of xlsx

    Thanks-PNRao!

  5. Hi. This is great help thanks! But I am trying to combine two codes but I cannot do it! I would like the macro to save the workbook as a file name taken from a cell and also save in in a certain folder location.! Please can you help?!!

  6. PNRao
    November 29, 2014 at 7:44 PM — Reply

    Hi Jason,
    Assuming you have the Folder path at Range A1 of sheet1, and File name at Range A2:

    wkb.SaveAs Filename:=Sheets(“Sheet1”).Range(“A1″) &” &Sheets(“Sheet1”).Range(“A2″) &”.xlsx”

    Hope this helps!
    Thanks-PNRao!

  7. Chris
    January 7, 2015 at 3:02 AM — Reply

    Hi,
    Can I use a macro to save the excel file in a specific location based off of a specific cell within the document? Also, Could I have the macro change the name of the document based off of a different cell within the same document?

  8. PNRao
    January 12, 2015 at 9:38 PM — Reply

    Hi Chris,

    Yes, you can use SaveAs method of workbook to save the file with different name. Assuming you have the file name in the Cell A1.

    The below code will save the active workbook in the same path with name specified at A1.

    Dim strFilename As String
    strFilename = ActiveWorkbook.Path & " & Range("A1") & ".xlsm"
    ActiveWorkbook.SaveAs Filename:=strFilename, FileFormat:=52
    

    The below code will save the active workbook in the given path with file name mentioned with the full path at A1.

    Dim strFilename As String
    strFilename =Range("A1") & ".xlsm"
    ActiveWorkbook.SaveAs Filename:=strFilename, FileFormat:=52
    

    Thanks-PNRao!

  9. mo
    March 25, 2015 at 6:04 PM — Reply

    hi,

    i am trying to use this code but having some issues,

    i am using excel 2010 but the extension .xlsm nor .xlsx is working

    this code:

    If sFileSaveName False Then
    ActiveWorkbook.SaveAs sFileSaveName
    End If

    is saving a copy of the file but closes the original document to reopen the saved copy.

    please help

  10. PNRao
    April 1, 2015 at 7:06 PM — Reply

    Hi,

    SaveAs will save the file with the changes in the specified location. It will not neither close the old file nor open new file.
    when you open the file, it will always stores in the temporary memory, when you Save the file, this will just save the changes to the existing file – SaveAs will save the file in the specified location.

    Hope this clarifies your query.
    Thanks-PNRao!

  11. Saputro
    July 18, 2015 at 6:19 PM — Reply

    Hi
    How to keep text format when save as to *.csv or at least to show “keep using that format” question dialog with VBA

    Thanks

  12. :)
    November 27, 2015 at 4:56 PM — Reply

    save file as .xls…. for that first go to the “save as type”.. then choose “.xls” extension file… ur file automatically will b saved as “filename.xls”…

  13. DLoughry
    December 17, 2015 at 8:01 PM — Reply

    What code do I use so that the file saves to a folder in a users My Documents. Now, the folder might not exist the first time they are saving the file, so I would need to incorporate that as well into the code.

    Example path: C:UsersDocumentsWorkbook1.xlsx

    Thanks in advance!

  14. DLoughry
    December 17, 2015 at 8:02 PM — Reply

    What code do I use so that the file saves to a folder in a users My Documents. Now, the folder might not exist the first time they are saving the file, so I would need to incorporate that as well into the code.

    Example path: C:UsersDocumentsWorkbook1.xlsx

    Thanks in advance

  15. DLoughry
    December 17, 2015 at 8:05 PM — Reply

    The example path did not show correctly in my initial comment. Between Users and Documents it should show ” and between Documents and the file name it should show “.

    C:Users”Documents”Workbook1.xlsx

  16. DLoughry
    December 17, 2015 at 8:07 PM — Reply

    Argh…Ok. Where the quotes are should be username and New Folder respectively.

    Sorry for all the extra comments.

  17. Guz
    January 2, 2016 at 2:39 AM — Reply

    Great, it really helped me!!

  18. T.Lajos
    April 12, 2016 at 11:09 PM — Reply

    Hi,
    I tried several code to save my excxel file. All attemts including your “Save Workbook in the same location of the Macro (this) Workbook” results the same: I get a new but empty file (with your code workbookname.xls) in the same directory where workbook using ThisWorkbook.There is data in cells of original workbook but the saved one is empty…(excel 2007)..
    Could you Have please some idea what couses this curious phenomena?

  19. MK
    July 27, 2016 at 4:26 PM — Reply

    I have the same problem. Maybe sone ideas?

  20. Patrick Mahoney
    August 26, 2016 at 2:41 AM — Reply

    Hi to all,
    I am using Excel 2011 for Mac. In a macro file (.xlsm) triggered from my database, with an AutoOpen macro, I import data from my database, format the spreadsheet and then save it as a .xlsx file. My problem is that when the macro does a SaveAs, there is a dialog box telling me that the macros will be removed in the .xlsx file and then required that I click on the save button. How can I bypass that dialog and finish the save process without user intervention?

    My code:

    ThisFile = Range(“B2”).Value
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=ThisFile, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=True
    Range(“A1”).Select
    Application.DisplayAlerts = True
    Application.Quit

  21. Sub
    December 29, 2016 at 7:20 PM — Reply

    I am passing a password through the variable “f” and trying to protect the workbook but it is not working.
    Can you tell me how?
    ActiveWorkbook.Protect Password:=f, Structure:=True, Windows:=False

  22. Shane
    June 16, 2017 at 8:21 PM — Reply

    Hi All,

    I am trying to add in code to save the below to a shared drive with a date in the name of the file ie “abc 16.06.2017” Would also love to send a print screen in the body of the mail too – can anyone help with that?

    Thanks a mill

    Sub Mail_ControlSheet()

    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim Sourcewb As Workbook
    Dim Destwb As Workbook
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim OutApp As Object
    Dim OutMail As Object

    With Application
    .ScreenUpdating = False
    .EnableEvents = False
    End With

    Set Sourcewb = ActiveWorkbook

    ActiveSheet.Copy
    Set Destwb = ActiveWorkbook

    With Destwb
    Select Case Sourcewb.FileFormat
    Case 51: FileExtStr = “.xlsx”: FileFormatNum = 51

    End Select

    End With

    Set OutApp = CreateObject(“Outlook.Application”)
    Set OutMail = OutApp.CreateItem(0)

    With Destwb
    With OutMail
    .to = “xx@abc.com”
    .CC = ”
    .BCC = ”
    .Subject = “XX ” & Format(Date, “dd-mm-yyyy”)
    .Body = “Hi All,” & vbCrLf & vbCrLf & “XX.” & vbCrLf & vbCrLf & “Many Thanks” & vbCrLf & “Shane”
    .Attachments.Add “hbeu.adroot.hsbcgb001Redir GB USERS LAPTOP43960692DocumentsShanehello.xlsm.”
    .Display
    End With
    On Error GoTo 0
    .Close savechanges:=False
    End With

    End Sub

  23. George
    September 9, 2017 at 1:52 AM — Reply

    I am trying to save file RENT.xls in different folders:
    My Documents/Jan 17/ RENT.xls
    My Documents/Feb/RENT.XLS
    My Documents/Mar/RENT.xls
    etc
    etc

    Can someone help please?

  24. PNRao
    September 12, 2017 at 11:27 PM — Reply

    Here is the Macro to save the file into required folders using VBA.

    Sub sbSaveFileInToDifferentFolders()
    
    Set wb = Workbooks.Open("C:TempRENT.xls")
    
    MyFoldersArray = Array( _
    "C:TempFolderA", _
    "C:TempFolderB", _
    "C:TempFolderC" _
    )
    
    For iCntr = 0 To UBound(MyFoldersArray, 1)
        wb.SaveAs MyFoldersArray(iCntr) & " & wb.Name
    Next
    
    End Sub
    

    Thanks!

  25. hi,
    After saving the workbook in a specific folder as shown below
    Sub ExampleToSaveWorkbook()

    Workbooks. Add
    ‘Saving the Workbook
    ActiveWorkbook.SaveAs “G:LookupExercise.xlsx”
    ‘OR
    ‘ActiveWorkbook.SaveAs Filename:=”G:LookupExercise.xlsx”

    End Sub
    I am not able to see the content in the workbook why?. I am a little bit confused in the context can you explain please.
    Thanks

  26. Aaron
    February 14, 2019 at 11:48 PM — Reply

    I need help with the following. I need to save a copy of a workbook with the File Name and the Date (A Save at that moment), and then open that saved Copy. Currently the below code will Save the file and rename the document correctly (except it will do .xlsm.xslm and I cant fix this…) but when you open the document, there is no information. Its completely blank…. so its not a save as, its just opening a new file and naming based on my file.

    Can someone help me correct this code so that it saves all of my data, renames the file and opens it up once saved?

    Sub snwb()
    Dim thisWb As Workbook, d As Integer

    Set thisWb = ActiveWorkbook
    Workbooks.Add
    d = InStrRev(thisWb.FullName, “.”)
    ActiveWorkbook.SaveAs filename:=Left(thisWb.FullName, d – 1) & Format(Now, ” yyyy.mm.dd”) & Mid(thisWb.FullName, d) & “.xlsm”, FileFormat:=52

    ActiveWorkbook.Close savechanges:=False
    End Sub

  27. Aaron
    February 15, 2019 at 4:36 AM — Reply

    I have an updated code that seems to be working correct, however, I need this to work with Office 365. I need the file to save back to the same location on 365. Any ideas?

    Sub SaveToRelativePath()
    Dim relativePath As String
    relativePath = ThisWorkbook.path & ” & ActiveWorkbook.Name
    ActiveWorkbook.SaveAs filename:=ThisWorkbook.Name & ” FINAL BID” & “.xlsm”, FileFormat:=xlOpenXMLWorkbookMacroEnabled
    End Sub

  28. Sivaprakasam
    October 28, 2019 at 12:57 PM — Reply

    Hi can u provide the below u r VBA including view list (file size, created date and modified date), due to i have confusing the new file or old file.

    Save a Workbook to a Specific Folder

    Sub ExampleToSaveWorkbook()

    Workbooks.Add
    ‘Saving the Workbook
    ActiveWorkbook.SaveAs “C:WorkbookName.xls”
    ‘OR
    ‘ActiveWorkbook.SaveAs Filename:=”C:WorkbookName1.xls”

    End Sub

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

Сохранение файла рабочей книги Excel, существующего или нового, с помощью кода VBA. Методы Save и SaveAs объекта Workbook, параметр SaveChanges метода Close.

Сохранение существующего файла

Сохранить существующий открытый файл рабочей книги Excel из кода VBA можно несколькими способами. В примерах используется выражение ActiveWorkbook, которое может быть заменено на ThisWorkbook, Workbooks(«ИмяКниги.xlsx»), Workbooks(myFile.Name), где myFile — объектная переменная с присвоенной ссылкой на рабочую книгу Excel.

Простое сохранение файла после внесенных кодом VBA Excel изменений:

Сохранение файла под другим именем (исходная рабочая книга будет автоматически закрыта без сохранения внесенных изменений):

ActiveWorkbook.SaveAs Filename:=«C:ТестоваяНоваяКнига.xlsx»

Сохранить файл рабочей книги можно перед закрытием, используя параметр SaveChanges метода Close со значением True:

ActiveWorkbook.Close SaveChanges:=True

Чтобы закрыть файл без сохранения, используйте параметр SaveChanges метода Close со значением False:

ActiveWorkbook.Close SaveChanges:=False

Сохранение файла под другим именем при закрытии рабочей книги:

ActiveWorkbook.Close SaveChanges:=True, Filename:=«C:ТестоваяНоваяКнига.xlsx»

Если в примерах с методом Close параметр SaveChanges пропустить, будет открыто диалоговое окно с запросом о сохранении файла.

Новая книга сохраняется с указанием полного имени:

Workbooks.Add

ActiveWorkbook.SaveAs Filename:=«C:ТестоваяНоваяКнига.xlsx»

После этого к новой книге можно обращаться по имени: Workbooks ("НоваяКнига.xlsx").

Если не указать полное имя для сохраняемого файла:

Workbooks.Add

ActiveWorkbook.Save

тогда новая книга будет сохранена с именем и в папке по умолчанию, например: Книга1.xlsx, Книга2.xlsx, Книга3.xlsx и т.д. в папке «Документы».


Понравилась статья? Поделить с друзьями:
  • Say the word t pain
  • Saving word files as pdf files
  • Say the word spell it перевод
  • Say the word single
  • Say the word sing the song