How to Quit Microsoft Excel and Save Unsaved Documents Gracefully

Hey Folks,

@skillet asked how to do this in another thread, and I thought it worthwhile to split it off to a new topic.

This task can be done easily with AppleScript, although I’m testing in Office 2011 (not 2016) and therefore can’t be certain M$ hasn’t bungled something in the newest version.

----------------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2018/04/21 22:45
# dMod: 2018/04/21 22:50
# Appl: Microsoft Excel
# Task: Save Excel Workbooks and Quit Excel
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @Microsoft_Excel, @Save, @Excel, @Workbooks, @Quit
----------------------------------------------------------------

tell application "Microsoft Excel"
   if (saved of workbooks) contains false then
      save every workbook
   end if
   quit
end tell

----------------------------------------------------------------

This can have unexpected consequences in Office 2011, because previously unsaved workbooks will save with the current name to the last save destination.

It’s possible to check and see if any workbooks haven’t been saved to disk though, so you can do something like this to stop the script.

----------------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2018/04/21 22:45
# dMod: 2018/04/21 23:20
# Appl: Microsoft Excel
# Task: Save Excel Workbooks with Error-Checking and Quit Excel.
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @Microsoft_Excel, @Save, @Excel, @Workbooks, @Quit
----------------------------------------------------------------

try
   
   tell application "Microsoft Excel"
      
      set pathList to path of workbooks
      
      if pathList contains "" then
         error "One or more Workbooks have NOT been saved to disk!"
      end if
      
      if (saved of workbooks) contains false then
         save every workbook
      end if

      quit
      
   end tell

   return "SUCCESS!" --> In case you want to save the outcome to a variable for flow-control.
   
on error e number n
   set e to e & return & return & "Num: " & n
   if n ≠ -128 then
      try
         tell application (path to frontmost application as text) to set ddButton to button returned of ¬
            (display dialog e with title "ERROR!" buttons {"Copy Error Message", "Cancel", "OK"} ¬
               default button "OK" giving up after 30)
         if ddButton = "Copy Error Message" then set the clipboard to e
      end try

      return "ERROR!" --> In case you want to save the outcome to a variable for flow-control.

   end if
end try

----------------------------------------------------------------

-Chris

1 Like

Works perfect in both version I just tested both AppleScript in both versions Office 2011 and 2016 (you of course knew it works in 2011).

You're a nerd , that's pretty cool, I'll add that to my restart a restart the computer macro.

1 Like