A person in the Word for Developers forum brought an important bug to our attention last week. When documents are opened/created then closed the
Documents collection does not keep proper track. The index value is not reduced correctly (there are more documents in the collection than there should be) and some document names are missing while others are duplicated. (The thread with repro code sample can be found here.)
Documents collection is not some obscure object - it’s central to file maintenance. That it does not function correctly is a serious issue. Microsoft appears to have been aware of it for some time, but hasn’t bothered to document the issue or correct it in Word 2010. The
Documents collection does, however, work correctly in all previous versions and in Word 2013.
I began to look for a reasonably efficient and reliable workaround and stumbled on an interesting fact: If the
DocumentClose events are actively being monitored by an add-in that loads with Word, the repro code yields the correct results – the
Documents collection functions as it should.
It does not matter whether this is a COM, VSTO or VBA (document template) add-in. And the code in the events doesn’t need to do anything special or useful. Just the fact that the events “trigger” from the very moment Word starts seems to keep the
Documents collection “honest”.
If you’re a VBA programmer, go to the VBA Editor and activate the
ThisDocument module from the Normal project, “Microsoft Word objects”. In the code window, select “Document” from the dropdown list on the left.
A stub for the event
Document_New will be created immediately. From the list on the right, also select
Document_Open and then
Document_Close. You can type in a commented line explaining what this is for. Save the changes, quit the VBA Editor and quit Word. The next time you start Word the Documents collection should function correctly.
Here’s my test code:
Private Sub Document_Close() 'Keeping the Documents collection working correctly... End Sub Private Sub Document_New() 'Keeping the Documents collection working correctly... End Sub Private Sub Document_Open() 'Keeping the Documents collection working correctly... End Sub