I’ve encountered a group of weird problems while trying to do something that seems simple: closing a document in a macro.
Here’s the situation. My application may be used in several Word documents at once, any of which may use a special temporary document as a scratch area. The temporary document is created automatically when the application’s first “real” document is opened. It should be closed automatically when the application’s last document is closed.
The first problem I discovered is that Word calls its event macros inconsistently. When I close a document from the menu, it calls FileClose. When I close a document by clicking the close box, it does not call FileClose, but it calls Close_Document. And when I close the last document opened, it calls both.
This creates a nightmare for my program logic. To ensure that my “on close” logic will be executed no matter how a document is closed, I must call it from both FileClose and Close_Document. But then, when I close the last document, it is executed twice. I haven’t figured out a clean, reliable way to detect when this is happening and avoid doing things twice that should only be done once.
The second problem is that the sequence of operations breaks Word’s Multiple Document Interface logic. This happens when only two documents remain open, one being an application document and the other the temporary document. Apparently what happens is this: when I close the last application document, Word says to itself, “OK, this is not the last document open, so I should close the window when I close the document.” Then my close logic closes the temporary document, so that by the time Word gets around to closing the application document, it IS the last document. Word closes the window along with the document, leaving no document windows open, but doesn’t shut itself down! (If the VBA editor window is open, stays open.) Word then crashes.
I’m looking for some way to be sure that the temporary document is closed along with the last application document, and also to keep Word from climbing into a hole and then covering itself up!