Show-N-Tell Thursday - Closing a Document in an Office Application Programmatically

February 16 2006

ShowAndTell.jpg For many years, I have been showing a very simple technique to close an Office document opened programmatically. For example:

Set hwd = CreateObject("Word.Application")
Call hwd.documents.open (documentpathandfilename)
'do something to the word document here
hwd.ActiveDocument.SaveAs (windowstemppath + attachmentfilename + extension)
hwd.ActiveDocument.Close
hwd.Quit

For some reason, Office 2003 Applications do not like this. I have seen errors and crashing using just the ActiveDocument.Close. Here is a way to prevent any issues:

Set hwd = CreateObject("Word.Application")
Call hwd.documents.open (documentpathandfilename)
'do something to the word document here
hwd.ActiveDocument.SaveAs (windowstemppath + attachmentfilename + extension)
Call hwd.documents(documentfilename).close(0,1)
hwd.Quit

A very simple change to one line of the code. Instead of relying on the ActiveDocument property, we are closing the document directly.

Hope this helps some of you out there!