Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, and 2013. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Running a Macro when a Workbook is Closed.

Running a Macro when a Workbook is Closed

by Allen Wyatt
(last updated July 11, 2015)

9

You can cause Excel to run a macro automatically whenever a particular workbook is closed. For instance, when the workbook is closed you might want to run a macro that asks the users if they want to perform some task, such as saving the day's data to another file.

In order to run a macro automatically when a workbook is closed, all you need to do is name the macro Auto_Close(). Thus, the following example macro is run automatically whenever the workbook containing it is closed:

Sub Auto_Close()
    Dim intStatusState As Integer

    intStatusState = Application.DisplayStatusBar
    Application.DisplayStatusBar = True
    Application.StatusBar = "Examining transactions."
    DetermineTransactions
    Application.StatusBar = "Posting transactions."
    PostTransactions
    Application.StatusBar = False
    Application.DisplayStatusBar = intStatusState
End Sub

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (10372) applies to Microsoft Excel 2007, 2010, and 2013. You can find a version of this tip for the older menu interface of Excel here: Running a Macro when a Workbook is Closed.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Turning Off Spell Checking

For some documents, you may not want spell checking turned on. There are two ways that you can turn it off, depending on ...

Discover More

Text Truncated in PivotTable

When you create a PivotTable based on data that contains lots of text, you may be surprised to find that your text is ...

Discover More

Adding Common Line Spacing Options

Sometimes the options presented by Word's tools don't exactly meet our formatting needs. Rather than changing the tools ...

Discover More

Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!

More ExcelTips (ribbon)

Creating and Naming a Worksheet Using a Macro

You can use macros to make your common Excel tasks easier and faster. For instance, if you routinely need to create new ...

Discover More

Using Named Ranges in a Macro

Named ranges are a great capability provided by Excel. You can define all sorts of named ranges in a workbook, but how do ...

Discover More

Automatically Enabling Macros for Specific Workbooks

On your system you may have workbooks that contain macros you know are safe to use. Microsoft provides two things you can ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is five minus 4?

2017-10-04 09:52:02

Santanu Sadhu

Thanks


2017-08-23 03:27:20

hardus

Good day, can someone help me? I'm using Excel 2010. I want to print a report every morning 6AM. Currently this report print only once after opening it. The next day this report don't want to print.
Private Sub Workbook_Open()

Select Case Weekday(Date)
Case 1, 2, 3, 4, 5, 6, 7

Application.OnTime TimeValue("06:00:00"), "PRINT_REPORT"

End Select
Application.OnTime ("05:50:00"), "Workbook_Open"

End Sub


Sub PRINT_REPORT()
'
' PRINT_REPORT

ActiveWindow.SelectedSheets.PrintOut Copies:=1
End Sub



2016-11-14 23:57:00

Jeni

My macro checks for the excel version installed on workbook_Open(). if it is a lower version than excel 2010 then I am calling Workbook.close to close the excel file. But it is closing the Excel application and restarting by itself.

I just want to close my excel workbook alone and to leave the excel application opened.

Looking forward to get help on this.
Thanks


2016-06-18 12:57:03

Nadesan MM

Hi,
I have the following macro.

Sub Send_Range()

' Select the range of cells on the active worksheet.
ActiveSheet.Range("B5:I25").Select
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Today = Format(Now(), "dd-mm-yyyy")

' Show the envelope on the ActiveWorkbook.
ActiveWorkbook.EnvelopeVisible = True

' Set the optional introduction field thats adds
' some header text to the email body. It also sets
' the To and Subject lines. Finally the message
' is sent.
With ActiveSheet.MailEnvelope
.Introduction = "Hi Team," & vbNewLine & "Please find the below status of HPQC Defect we raised as on date " & Today & vbNewLine & vbNewLine & "With regards," & vbNewLine & "NADESAN MM" & vbNewLine & vbNewLine & "Note:This is a macro genarated mail"
.Item.To = "nadesan.mm@unilever.com"
.Item.Subject = "HPQC Defect Status |Clarity ID:2007320| AC UAT | As on " & Today
.Item.display
End With

End Sub

The above macro should run at a specified time everyday, even the work book is closed or opened.

could you please help on this.

regards.
NADESAN MM


2015-10-07 05:28:58

balthamossa2b

@habib

Something like this:




Private Sub Workbook_Open()
Dim d As Date
Dim f As Date

d = DateValue(Now)
f = DateValue("20/10/2015")

If (f - d) > 10 Then Call KillMyFile
End Sub


Sub KillMyFile()
On Error GoTo ErrorHandler
With ActiveWorkbook
If .Path <> "" Then
.Saved = True
.ChangeFileAccess xlReadOnly
Kill ActiveWorkbook.FullName
Application.Quit
End If
End With
Exit Sub

ErrorHandler:
MsgBox "Fail to delete file: " & ActiveWorkbook.FullName
End Sub

(macro up there from http://www.excelforum.com/excel-programming-vba-macros/561546-delete-kill-active-workbook-on-close-possible.html )




Paste this code in your Workbook code zone for the file you want to delete and set "f" as you see fit. When someone opens the book it'll disappear.

However, you should know that holding SHIFT disables any automatic macro execution, so if you want to use this as a security measure (or anything VBA-based, for that matter) it won't work.

Also careful where you paste this, as you won't be able to recover what you delete.


2015-10-06 08:59:28

habib

hi,
I like to know that how can i make an excel files for others which it is erase after for example 10 days via a macro.


2015-07-13 11:58:02

Scott Renz

Oh, I thought that this was going to be about code that tries to run a macro that is in another workbook, but that other workbook is closed.


2015-07-12 11:58:17

Spreadsheet1.com

Indeed, in Excel 2010 or later, there is a new event:

Private Sub Workbook_AfterSave(ByVal Success As Boolean)

If Success Then
MsgBox ("The workbook was successfully saved.")
End If

End Sub


2015-07-11 05:46:39

Willy Vanhaelen

The Auto_Close macro is a relic of old Excel versions. This is what Help (Excel 2007) says:

"Workbook.RunAutoMacros Method
Runs the Auto_Open, Auto_Close, Auto_Activate, or Auto_Deactivate macro attached to the workbook. This method is included for backward compatibility. For new Visual Basic code, you should use the Open, Close, Activate and Deactivate events instead of these macros."

In this case better use one of these events in the ThisWorkbook code page:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
'code goes here
End Sub

or

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
'code goes here
End Sub


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.