Vba excel do not save changes

Summary

In Microsoft Excel, you can create a Microsoft Visual Basic for Applications (VBA) macro that suppresses the Save Changes prompt when you close a workbook. This can be done either by specifying the state of the workbook Saved property, or by suppressing all alerts for the workbook.

More Information

NOTE: Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure. However, they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. 

To prepare for implementing either of the examples below, perform these steps first:

  1. Start Excel and open a new workbook.

  2. Press ALT+F11 to start the Visual Basic editor.

  3. On the Insert menu, click Module.

  4. Type the sample macro code into the module sheet.

  5. Press ALT+F11 to return to Excel.

  6. In Microsoft Office Excel 2003 and in earlier versions of Excel, choose Macro from the Tools menu, and then click Macros.

    In Microsoft Office Excel 2007, click Macros in the Code group on the Developer tab. 

    If the Developer tab is not available

    , consider doing this:

        a. Click the Microsoft Office Button, and then click Excel Options.

        b. In the Popular category, under Top options for working with Excel, click to select the Show
            Developer tab in the Ribbon
     check box, and then click OK.

  7. Select the macro that you want, and then click Run.

The Saved property returns the value False if changes have been made to a workbook since it was last saved.

You can use the reserved subroutine name Auto_Close to specify a macro that should run whenever a workbook is closed. In doing so, you can control how the document is handled when the user closes the documents in Excel.

Example 1: Close the workbook without saving changes

To force a workbook to close without saving any changes, type the following code in a Visual Basic module of that workbook:
 


    Sub Auto_Close()


        ThisWorkbook.Saved = True


    End Sub

When the Saved property is set to True, Excel responds as though the workbook has already been saved and no changes have occurred since that last save.

The DisplayAlerts property of the program can be used for the same purpose. For example, the following macro turns DisplayAlerts off, closes the active workbook without saving changes, and then turns DisplayAlerts on again.


    Sub CloseBook()


        Application.DisplayAlerts = False


        ActiveWorkbook.Close


        Application.DisplayAlerts = True


    End Sub

You can also use the SaveChanges argument of the Close method.

The following macro closes the workbook without saving changes:

   

Sub CloseBook2()


   

   

ActiveWorkbook.Close savechanges:=False

   

End Sub

Example 2: Close the workbook and save the changes

To force a workbook to save changes, type the following code in a Visual Basic module of that workbook:
 


    Sub Auto_Close()


        If ThisWorkbook.Saved = False Then


            ThisWorkbook.Save End If


    End Sub

This subprocedure checks to see if the file Saved property has been set to False. If so, the workbook has been changed since the last save, and those changes are saved.

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

I have a script that opens an excel file and runs a macro, then quits the file. Since the file is in read only mode, and the script makes temporary changes to the file, when the script calls myExcelWorker.Quit() excel asks if I want to save my changes and I must click ‘no’. Is there any way to exit the program and skip this box?

' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")

' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application") 

myExcelWorker.Visible = True

' Tell Excel what the current working directory is 
' (otherwise it can't find the files)
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = WshShell.CurrentDirectory
myExcelWorker.DefaultFilePath = strPath

' Open the Workbook specified on the command-line 
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "BugHistogram_v2.xlsm"

Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)

' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "CreateImagesButton_Click"
on error resume next 
   ' Run the calculation macro
   myExcelWorker.Run strMacroName
   if err.number <> 0 Then
      ' Error occurred - just close it down.
   End If
   err.clear
on error goto 0 

' oWorkBook.Save ' this is ignored because it's read only 

myExcelWorker.DefaultFilePath = strSaveDefaultPath

' Clean up and shut down
Set oWorkBook = Nothing

' Don’t Quit() Excel if there are other Excel instances 
' running, Quit() will 
' shut those down also
if myExcelWorker.Workbooks.Count = 0 Then
   myExcelWorker.Quit
End If

myExcelWorker.Quit()

Set myExcelWorker = Nothing
Set WshShell = Nothing

brettdj's user avatar

brettdj

54.6k16 gold badges113 silver badges176 bronze badges

asked Jul 3, 2014 at 20:43

Cassandra McCarthy's user avatar

ActiveWorkbook.Close False (to close the workbook)

Application.Quit (to quit Excel — doesn’t prompt to save changes)

From Microsoft Support’s How to suppress «Save Changes» prompt when you close a workbook in Excel:

To force a workbook to close without saving any changes, type the
following code in a Visual Basic module of that workbook:

Sub Auto_Close()
    ThisWorkbook.Saved = True
End Sub

Because the Saved property is set to True, Excel responds as though the workbook has already been saved and no changes have
occurred since that last save.

The DisplayAlerts property of the program can be used for the same
purpose. For example, the following macro turns DisplayAlerts off,
closes the active workbook without saving changes, and then turns
DisplayAlerts on again.

Sub CloseBook()
    Application.DisplayAlerts = False
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
End Sub

You can also use the SaveChanges argument of the Close method.

The following macro closes the workbook without saving changes:

Sub CloseBook2()
    ActiveWorkbook.Close savechanges:=False
End Sub

answered Jul 3, 2014 at 20:47

Isaac G Sivaa's user avatar

Isaac G SivaaIsaac G Sivaa

1,2894 gold badges15 silver badges32 bronze badges

1

The answer you have above is for VBA — you can address this in your VBS directly by using

oWorkBook.Close False
Set oWorkBook = Nothing

in place of

Set oWorkBook = Nothing

answered Jul 5, 2014 at 11:45

brettdj's user avatar

  • #1

I have a working macro that opens a workbook, does some stuff, and then closes it. But, when I run the macro, it prompts me as to whether or not I want to save changes. Is there a way I can write into the macro not to save the changes?

Currently the code I’m using to close the workbook is the following:

Windows(«MTAP.xls»).Activate
ActiveWindow.Close

If you know better code, and also a way to tell it not to save changes, I’d be very appreciative!

Will the fill handle fill 1, 2, 3?

Yes! Type 1 in a cell. Hold down Ctrl while you drag the fill handle.

  • #2

change to

Code:

Workbooks("MTAP.xls").Close False

  • #3

Thanks jindon!

I am encountering one other problem with this macro though, and was wondering if you or someone else could help:

Range(«tempchart!A2:F97»).Copy
Sheets(«Master»).Unprotect
Range(«Master!A2:F97»).Insert Shift:=xlDown
Sheets(«Master»).Protect DrawingObjects:=True, Contents:=True, Scenarios:=True

Doesn’t work. I’m trying to just copy a range of cells onto a protected sheet. When the macro runs, it inserts the specified cells, but not the values I copied along with it. Any idea why?

  • #4

Because unprotecting worksheet after copy will empty clipboard.
Change the order…

Code:

Sheets("Master").Unprotect
Range("tempchart!A2:F97").Copy
Range("Master!A2:F97").Insert Shift:=xlDown
Sheets("Master").Protect DrawingObjects:=True, Contents:=True, Scenarios:=True

Knockoutpie

Knockoutpie

If an Excel file that you have created requires macros to be activated in order to work properly and you would like to prevent any modifications to the file from being saved, it’s possible to do this and it will only take a second.

Open your file with macros disable and paste the following code into ThisWorkbook:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Cancel = True 'Cancels any request to save the file
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Application.ThisWorkbook.Saved = True 'Tells Excel that the file has already been saved (this prevents Excel from requesting that you save the file when you close it)
End Sub

All you have left to do is to save your file (you will always be able to save the file as long as macros are disabled).

When working with an Excel workbook, there are a few basic operations that any user needs to know how to carry out. The following are 2 of the most important ones:

  1. Opening a workbook.
  2. Closing a workbook.

Excel VBA Tutorial about how to close a workbookThese 2 actions are just as important if you’re working with Visual Basic for Applications.

In this tutorial, I focus on topic #2: How you can easily close an Excel workbook with VBA.

For these purposes, in the first few sections of this tutorial, I introduce some VBA constructs that help you create macros that close workbooks. My focus is, mainly, in the Workbook.Close method. However, I also introduce the Workbooks.Close method, which allows you to quickly close all open workbooks. At the end of that first section, I discuss the topic of closing Excel workbooks without prompts and introduce some of the most common ways of achieving this.

In the second section of this post, I go through 8 macro code examples. These VBA code samples use the constructs introduced in the first section for purposes of closing Excel workbooks in different situations. All of the macros are accompanied by an explanation. You can easily adjust the code samples in order to fit your own needs.

This Excel VBA Close Workbook Tutorial is accompanied by an Excel workbook containing the macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Please use the following table of contents to quickly navigate to the section that interests you the most. For best results, you may want to read the whole blog post.

Let’s start by taking a look at the…

Workbook.Close Method

You can use the Workbook.Close method for purposes of closing the applicable workbook object.

The basic syntax of Workbook.Close is as follows:

expression.Close(SaveChanges, Filename, RouteWorkbook)

The following are the applicable definitions for purposes of the statement above:

  • expression: Workbook object.
  • SaveChanges: Optional argument. You use SaveChanges for purposes of specifying whether to save changes (True) or not (False).
  • Filename: Optional argument. Filename allows you to specify the filename used by Excel when saving.
  • RouteWorkbook: Optional argument. Makes reference to workbook routing. In that context, it allows you to determine whether the workbook is sent to the next recipient (True) or not (False).

Since expression represents a Workbook object, I simplify the syntax above to the following:

Workbook.Close(SaveChanges, Filename, RouteWorkbook)

Let’s start by taking a closer look at the 3 parameters (SaveChanges, Filename and RouteWorkbook) above. After covering these arguments, I provide a few additional comments about the Workbook.Close method.

SaveChanges Parameter

You use the SaveChanges parameter to specify whether Visual Basic for Applications saves changes to the workbook (or not) when the workbook:

  1. Has unsaved changes.
  2. Doesn’t appear in any other open windows.

Both of these conditions must be met in order for VBA to consider SaveChanges. In other words, VBA ignores SaveChanges in the following situations:

  • When there aren’t any unsaved changes to the workbook.
  • Where there are changes to the workbook, but the workbook appears within other open windows.

SaveChanges is an optional argument. You generally use the following values when working with it:

  • True: Close workbook and save changes.
  • False: Close workbook without saving changes.

If you omit the SaveChanges parameter and the relevant workbook contains unsaved changes, Excel displays a dialog box. This dialog asks the user whether the changes should be saved or not.

Want to save your changes to workbook

Filename Parameter

Filename allows you to specify the filename under which Excel saves the changes to the closed workbook.

Filename is an optional parameter. Additionally, Filename is only relevant if you set SaveChanges to True. Whenever you set the SaveChanges parameter to False, the changes aren’t saved at all.

If you omit Filename and the workbook has no previous filename, Excel displays the Save As dialog box and asks the user to provide the filename.

Save As dialog launched when no Filename for Workbook.Close

Despite the above, if you want to ensure that a particular workbook is saved under a certain name and close it, you can generally proceed as follows:

  1. Use the Workbook.SaveAs method to save the workbook; and
  2. Close the workbook by using the Workbook.Close method.

This way of proceeding is suggested by authorities such as author Richard Mansfield (in Mastering VBA for Microsoft Office 2016). Some of the advantages of using the SaveAs method (vs. the Filename parameter) for these purposes are the following:

  1. Ensures that the workbook is always saved under the filename you specify.
  2. Allows you to take advantage of the 10 parameters of the SaveAs method. By using these parameters, you can specify items such as (i) file format, and (ii) protection password.

RouteWorkbook Parameter

The RouteWorkbook parameter is associated to workbook routing. You can use RouteWorkbook to specify whether the workbook is routed to the next recipient or not.

RouteWorkbook is optional.

The main rules that Visual Basic for Applications uses to determine how to deal with RouteWorkbook are as follows:

  1. If there’s no need to send the workbook to the next recipient, VBA ignores RouteWorkbook.

    For example, the workbook doesn’t need to be routed if (i) there’s no routing slip attached, or (ii) the routing has already occurred.

  2. If the workbook needs to be routed, VBA applies the value you specify for RouteWorkbook. You can use the following 2 values:
    1. True: VBA routes the workbook to the next recipient.
    2. False: The workbook isn’t sent.
  3. If you omit RouteWorkbook and the workbook need to be send, Excel asks the user whether the workbook is routed or not.

Workbook.Close Method And Auto_Close Macros

Auto_Close macros aren’t executed when you close the workbook from VBA. This is relevant if your workbook uses Auto_Close macros (vs. the BeforeClose event) for purposes of automatically running a macro before a workbook closes. The Workbook.Close method does trigger the BeforeClose event.

If you need to deal with Auto_Close macros and want the macro to be executed when you use the Workbook.Close method, use the Workbook.RunAutoMacros method.

Workbook.Close Method And Add-Ins

Usually, you install and uninstall add-ins through the Add-Ins dialog.

You can also open and close add-ins. In other words, you can theoretically apply the Workbook.Close method to an add-in.

As a consequence of the above, if you’ve accessed an add-in as a workbook (vs. using the Add-Ins dialog box), you can close it with the Close method. However, as a general rule, this isn’t the most appropriate way to deal with add-ins.

The reason for this is explained by Excel authorities Dick Kusleika and Mike Alexander in Excel 2016 Power Programming with VBA, as follows:

Using the Close method on an installed add-in removes the add-in from memory but does not set its Installed property to False. Therefore, the Add-Ins dialog box still lists the add-in as installed, which can be confusing.

Therefore, as a general rule, use the AddIn.Installed property for purposes of installing and removing add-ins.

Workbooks.Close Method

You can also apply the Close method to the collection of all open Excel workbooks. In other words, you can use the Workbooks.Close method to close all Excel workbooks at once.

The basic syntax of Workbooks.Close is as follows:

expression.Close

“expression” represents the Workbooks collection. Therefore, I simplify the above as follows:

Workbooks.Close

The Workbooks.Close method is, to a certain extent, similar to the Workbook.Close method I explain above. For example, Auto_Close macros aren’t executed when you close a workbook with either of these methods. Therefore, my comments above regarding Auto_Close macros and Workbook.Close are also generally applicable to Workbooks.Close.

There’s, however, a very important difference between Workbook.Close and Workbooks.Close:

Workbooks.Close takes no parameters. As I explain above, Workbook.Close has 3 parameters (SaveChanges, Filename and RouteWorkbook).

As a consequence of the above, if you want to use any (or all) of the parameters I describe above while closing all open workbooks, you generally have to rely on loops.

Further below, I provide macro code examples that you can use to close all open workbooks using either of these 2 methods:

  1. Workbooks.Close.
  2. Workbook.Close (+ loops).

Excel VBA To Close Workbook Without Prompts

In certain cases, you want to ensure that Excel closes a particular workbook without showing any prompts.

When working with the Close VBA method, the prompts that you usually have to deal with ask one of the following questions:

  1. Should Excel save the changes?

    Dialog: Want to save changes to Book?

  2. What filename should Excel use?

    Excel Save As dialog box

There are a few different ways in which you can handle this using Visual Basic for Applications. The most common ways of tackling this issue are the following 4:

  1. Saving the workbook prior to using the Close method.
  2. Appropriately using the SaveChanges and Filename parameters of the Workbook.Close method.
  3. Using the Application.DisplayAlerts property.
  4. Setting the Workbook.Saved property to True.

I cover the topic of how to save a workbook using VBA (#1 above) in a separate blog post that you can find in the Archives. I cover both the SaveChanges and Filename arguments (#2 above) in this tutorial.

Therefore, in the following sections, I introduce the remaining VBA constructs #3 (Application.DisplayAlerts) and #4 (Workbook.Saved). Using either of these 2 properties results in Excel closing the workbook without prompts. In both cases, Excel closes the file without saving the changes.

Application.DisplayAlerts Property

The Application.DisplayAlerts property allows you to specify whether or not Excel displays certain prompts and alerts. For these purposes, you can set Application.DisplayAlerts to either of the following values:

  1. True: The default value. Excel displays alerts and messages.
  2. False: The alerts and messages aren’t displayed. If a particular alert or message requires a user response, Excel uses the default.

The basic syntax of Application.DisplayAlerts is as follows:

expression.DisplayAlerts

“expression” is the Excel Application object. Therefore, I simplify the above as follows:

Application.DisplayAlerts

Macro example #7 below uses the Application.DisplayAlerts property for purposes of closing a workbook without prompts. There are, however, other (better) ways of using VBA to close an Excel workbook without displaying prompts. I provide further explanation of this matter in the relevant section (for macro sample #7) further below.

Workbook.Saved Property

From a general perspective, the Workbook.Saved property indicates whether changes have been made to a particular Excel workbook since the last time it was saved. In other words, Workbook.Saved indicates whether the workbook has unsaved changes.

The basic syntax of Workbook.Saved is as follows:

expression.Saved

“expression” is a Workbook object. Therefore, I simplify the above as follows:

Workbook.Saved

The Saved property is, however, read/write. Therefore, you can set Workbook.Saved to either of the following values:

  1. True: No changes have been made since the last time the workbook was saved.
  2. False: Changes have been made.

By setting Saved to True prior to closing a workbook, you can close a workbook without Excel displaying a prompt. In such case, the changes to the workbook aren’t saved.

I provide a practical code example showing how you can easily do this further below (macro example #8).

In the following sections, I provide 8 macro code examples that allow you to close an Excel workbook using VBA. These 8 macro samples cover several of the most common situations you’re likely to encounter.

The Sub procedure examples I provide work with the active workbook. For these purposes, I use the Application.ActiveWorkbook property (ActiveWorkbook). By replacing the object reference, you can easily adjust these macros in order to work with other workbooks.

Macro Code Example #1: Excel VBA Close Workbook

At the most basic level, you can use a statement with the following structure to close an Excel workbook:

Workbook.Close

The following sample macro (Close_Workbook) closes the active workbook:

ActiveWorkbook.Close

The macro example has a single statement that follows the structure I describe above:

ActiveWorkbook.Close

This statement is built by using the following items:

  1. ActiveWorkbook: The Application.ActiveWorkbook property returns the active workbook.
  2. Close: The Close method closes the active workbook returned by item #1.

Macro Code Example #2: Excel VBA Close Workbook Without Saving Changes

If you want to close a workbook without saving changes, you can use a statement that uses the following syntax:

Workbook.Close SaveChanges:=False

The following macro example (Close_Workbook_Without_Saving_Changes) closes the active workbook without saving changes:

ActiveWorkbook.Close SaveChanges:=False

The following are the items within the macro’s single statement:

  1. ActiveWorkbook: The active workbook.
  2. Close: The Close method.
  3. SaveChanges:=False: The SaveChanges parameter of the Workbook.Close method is set to False. Therefore, Excel doesn’t save changes prior to closing the workbook.

This macro is substantially the same as the previous example #1. The only new item is the SaveChanges argument (#3).

Macro Code Example #3: Excel VBA Close Workbook And Save Changes

You can use the following statement structure to close a workbook and save the changes:

Workbook.Close SaveChanges:=True

The following sample Sub procedure (Close_Workbook_Save_Changes) closes the active workbook and saves changes:

ActiveWorkbook.Close SaveChanges:=True

The only statement within the macro has the following 3 components:

  1. ActiveWorkbook: Reference to the active workbook.
  2. Close: The Close method.
  3. SaveChanges:=True: Sets the SaveChanges parameter of Workbook.Close to True. As a consequence of this, Excel saves the changes when closing the workbook.

This procedure is almost identical to macro sample #2 above. The only difference is the value to which the SaveChanges parameter (#3 above) is set (True vs. False).

Macro Code Example #4: Excel VBA Close Workbook And Save Changes With Filename

The VBA statement structure that I show below allows you to do the following:

  1. Save the workbook before closing.
  2. Set the filename that Excel uses if the workbook has no previously associated filename.

The following VBA statement structure allows you to do the above:

Workbook.Close SaveChanges:=True, Filename:=”fileNameString”

For these purposes, “fileNameString” is the file name you want Excel to use.

As I mention further above (section about the Filename parameter), using the statement I provide in this section doesn’t always result in the workbook being saved with the filename you want. In order to ensure that the workbook is saved always under the desired filename, you can generally use the Workbook.SaveAs method prior to calling the Workbook.Close method.

The following macro example (Close_Workbook_Save_Changes_Filename) closes the active workbook and saves changes under the specified filename. The filename under which the workbook is saved (if applicable) is “Excel VBA Close Workbook”.

ActiveWorkbook.Close SaveChanges:=True, Filename:="Excel VBA Close Workbook Test"

The statement within the macro above has the following components:

  1. ActiveWorkbook: Application.ActiveWorkbook property.
  2. Close: Workbook.Close method.
  3. SaveChanges:=True: Sets the SaveChanges parameter of Workbook.Close to True.
  4. Filename:=”Excel VBA Close Workbook”: The Filename argument of the Close method. Specifies that the filename that Excel uses is “Excel VBA Close Workbook”.

This sample macro is very similar to the previous example #3. The only new item is the Filename parameter (#4).

Macro Code Examples #5 And #6: Excel VBA Close All Workbooks

In this section, I provide 2 macro examples that you can use to close all Excel workbooks at once.

As I mention above, you can use the Workbooks.Close method in order to close all the members of the Workbooks collection (i.e. all open workbooks). Therefore, you can use the following statement for purposes of closing all open Excel workbooks:

Workbooks.Close

The following macro code sample (Close_All_Workbooks) closes all workbooks with the Workbooks.Close method. The single statement within this macro is the one I explain above.

Workbooks.Close

However, as I explain above, Workbooks.Close takes no parameters.

The Workbook.Close method does take parameters. The Workbook.Close method works with only one workbook at a time. In order to close all open workbooks at once, you can use a For Each… Next loop. The resulting structure of the relevant VBA loop is as follows:

For Each Workbook In Workbooks

Workbook.Close

Next Workbook

The following procedure example (Close_All_Workbooks_Loop) uses the Workbook.Close method and a For Each… Next loop to close all workbooks:

For Each... Next Loop and myWorkbook.Close

The process followed by this macro to close all open workbooks is as follows:

  1. Close the first open workbook.
  2. Check whether there are elements left within the collection of open workbooks.
  3. If there are open workbooks left:
    1. Close the next workbook.
    2. Repeat step #2 above.
  4. If there are no open workbooks left (step #2), exit the For Each… Next loop and end the macro.

The following diagram illustrates this procedure:

Loop diagram: Close first workbook and More workbooks and Close next workbook

Let’s take a closer look at each of the lines of code within this sample macro:

Line #1: Dim myWorkbook As Workbook

The Dim statement declares the myWorkbook object variable.

Line #2: For Each myWorkbook In Workbooks

Opening statement of a For Each… Next loop. This repeats the execution of the statement within the loop (line #3 below) for each workbook within the Workbooks collection.

The 2 relevant items within this line of code are the following:

  1. myWorkbook: myWorkbook variable. Used to iterate through all the elements within the Workbooks collection (item #2).
  2. Workbooks: The Application.Workbooks property returns the collection of all open workbooks.

Line #3: myWorkbook.Close

This statement is exactly the same as that in macro sample #1 above. You can easily modify this statement to use the SaveChanges and/or Filename properties. Examples #2 through #4 are examples of how you can do this.

When within the For Each… Next loop, this line #3 results in Excel closing the applicable workbook. The closed workbook, therefore, is dependent on the current iteration of the loop.

Line #4: Next myWorkbook

Closing statement of the For Each… Next loop.

Macro Code Examples #7 And #8: Excel VBA Close Workbook Without Prompt

This section provides 2 macro code examples that allow you to close a workbook without prompts.

The first macro sample (#7) uses the following basic structure:

Application.DisplayAlerts = False

Workbook.Close

This results in Excel closing the workbook without prompts. Additionally, the workbook isn’t saved.

As I mention above when introducing the Application.DisplayAlerts property, you’re generally better off avoiding this particular VBA code structure. The other options I discuss in this tutorial (saving the workbook prior to calling Close, or using the SaveChanges and Filename parameters of Close) are more appropriate in most situations.

The following macro example (Close_Workbook_Without_Prompt_1) turns off Excel’s prompts and alerts prior to closing the workbook. Therefore, Excel closes the active workbook without prompts.

Application.DisplayAlerts = False. ActiveWorkbook.Close

This sample macro is composed of the following 2 statements:

  1. Application.DisplayAlerts = False: Sets the Application.DisplayAlerts property to False. As a consequence, Excel turns off prompts.
  2. ActiveWorkbook.Close: The Application.ActiveWorkbook property and the Workbook.Close method are used to close the active workbook.

The second macro within this section uses the following syntax:

With Workbook

.Saved = True

.Close

End With

By setting the Workbook.Saved property to True, you indicate that no changes have been made since the last time the workbook was saved. In other words, you’re telling Excel that the workbook you’re closing doesn’t need to be saved.

The following macro code sample (Close_Workbook_Without_Prompt_2) sets the Saved property to True prior to calling the Workbook.Close method. As a consequence of this, the active workbook is closed without displaying prompts.

ActiveWorkbook.Saved = True. ActiveWorkbook.Close

Let’s take a closer look at each of the lines of code within this sample Sub procedure:

Line #1: With ActiveWorkbook

Opening line for a With… End With block. As a consequence of this, the statements within the block (lines #2 and #3) work with the object specified in this line #1. That object is the active workbook (ActiveWorkbook).

Line #2: .Saved = True

Sets the Workbook.Saved property to True. Indicates that no changes have been made to the active workbook (in line #1 above) since last time the workbook was saved.

Line #3: .Close

Calls the Workbook.Close method. Closes the active workbook (in line #1 above).

Line #4: End With

Closing line of the End… End With statement.

Conclusion

After reading this Excel VBA tutorial, you have the knowledge you need to start crafting macros that quickly close Excel workbooks in several different scenarios.

In the first section of this tutorial, you read about the 2 VBA methods you can use to close Excel workbooks:

  1. Workbook.Close.
  2. Workbooks.Close.

In addition to reading about how you can easily use each of these methods, you’ve seen why most VBA Sub procedures rely on the Workbook.Close method. You’ve also read about how, by appropriately using the parameters of Workbook.Close or combining this method with other VBA constructs, you can specify how Excel acts when closing a workbook.

Finally, you’ve seen 8 examples of macro code that put the above VBA constructs and information in practice.

Overall, the information and examples within this tutorial allow you to easily and quickly create Excel macros that achieve a variety of objects. The following are some examples of what you can now do with Visual Basic for Applications:

  1. Close a particular Excel workbook.
  2. Close a workbook without saving changes.
  3. Close a workbook and save the changes. This includes the possibility of setting the filename Excel uses when saving.
  4. Close all open workbooks at once.
  5. Close an Excel workbook without any prompts.

This Excel VBA Close Workbook Tutorial is accompanied by an Excel workbook containing the macros I use in the examples above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Books Referenced In This Excel Tutorial

  • Alexander, Michael and Kusleika, Dick (2016). Excel 2016 Power Programming with VBA. Indianapolis, IN: John Wiley & Sons Inc.
  • Mansfield, Richard (2016). Mastering VBA for Microsoft Office 2016. Indianapolis, IN: John Wiley & Sons Inc.

Понравилась статья? Поделить с друзьями:
  • Vba excel dir file
  • Vba excel dim что это
  • Vba excel format column
  • Vba excel form activate
  • Vba excel for шаг