AppleScript to save active Microsoft Word document IFF there is one

applescriptms office

I use this with Keyboard Maestro to automatically save the front-most document in Microsoft Word whenever Word deactivates:

tell application "Microsoft Word"
    if it is running then
        save active document
    end if
end tell

This works great unless there is not an active document, in which case it throws an error.

I know I could ignore the error, but I would rather not.

I would like to know if there’s a proper AppleScript way to say something like “If active document exists, then save it.”

I tried Googling but only found this (what I have now).

Best Answer

You need to query Word for the count of document objects – active document is just a convenience shortcut to the frontmost one in that list. Unluckily, Word’s somewhat peculiar AppleScript implementation does not return an empty list object when there is no open document, but missing value (AppleScript’s take on nil) instead. Taking that into account, the following function queries Word for open documents:

on hasDocument()
  tell application "Microsoft Word"
    every document is not missing value
  end tell
end

– put that in front of your script and change your conditional to if it is running and my hasDocument() and you should be fine.