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

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

Sticking with the Dashes

By default, dashes don't "stick" to the text that follows them. Here's one way around this normal formatting convention.

Discover More

Different Ways of Inserting Dates

Word provides a couple of different ways you can insert the current date into a document. Which method should you choose? ...

Discover More

Envelopes and Labels Dialog Box Slow to Open

We all like Word to be snappy and responsive. Sometimes, though, it can be much slower than what we desire. One such time is ...

Discover More

Professional Development Guidance! Four world-class developers offer start-to-finish guidance for building powerful, robust, and secure applications with Excel. The authors show how to consistently make the right design decisions and make the most of Excel's powerful features. Check out Professional Excel Development today!

More ExcelTips (ribbon)

Creating Worksheets with a Macro

Using a macro to add worksheets to your workbook is easy. This tip provides two different methods you can use.

Discover More

Determining a Random Value

Random values are often needed when working with certain types of data. When you need to generate a random value in a macro, ...

Discover More

Installing the Date Picker

When creating your own user interfaces within Excel, the various developer controls can add a nice touch. One such control is ...

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 3 + 8?

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.