It transpires that I was mistaken when I wrote in my previous blog that the problems in automating Word 2010 had been solved. Even when defining the complete path to the template, I was receiving 'invalid variant operation' messages. After having wasted many hours trying to solve the problem - and trying to isolate the problem, I escalated the problem to the excellent Stack Overflow site.
I first thought that the problem was with the template, but when I saw that one of my programs worked with a certain template but that another didn't with a different template, I was inclined to believe that the problem was with accessing the bookmarks within the template. It turns out that I was wrong on all accounts.
Here is the answer which solved the problem; I quote it verbatim.
Word 2010 has a bug that is related to loading Normal.dotm (and maybe plugins too, who knows?). When you start Word 2010 as you would normally do, you see a splashscreen and Word performs some initialization, including loading Normal.dotm. When you start Word via automation - CreateOleObject('Word.Application') - it doesn't wait till Normal.dotm is loaded and returns immediately. But performing operations when Normal.dotm is still being loaded seems to crash Word. What I did to solve this problem is to make a loop that just waits for the template to load. You can also choose for a delay to give Word the time to initialize, but so far, the loop works.
Something like this:
wrdapp := CreateOleObject('Word.Application');// loop that waits for the normal template to loadwhile wrdapp.Templates.Count = 0 do Sleep(200);// continue operations
I added the 'sleep' command to one incalcitrant program, and the fix works! Now I have to go over all the programs and fix wherever Word is invoked, but this shouldn't be too difficult.
In retrospect, the 'invalid variant operation' message now becomes clear: I was trying to access something which hadn't yet been created, so of course the operation was invalid.
Now perhaps I can get back to creative programming instead of holding fingers in the dam and getting frustrated (never a good idea when debugging).
No comments:
Post a Comment