Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word 2010 automation: 'goto bookmark'

I have a program written in Delphi-7 which opens a new Word document which is based on a template.
Once the document is open, the automation jumps to a bookmark (predefined in the template) and adds some text there.
The following code works fine in Word 2003 but causes a invalid variant operation error message in Word 2010 (I have omitted try/except blocks for the sake of clarity).

wrdapp:= CreateOleObject ('Word.Application');
wrdDoc:= wrdapp.documents.add (wrdApp.Options.DefaultFilePath[wdUserTemplatesPath] + '1.dot'
wrdApp.selection.goto (wdGotoBookmark, unassigned, unassigned, 'B1')

If I replace the third line with

wrdDoc.bookmarks.item ('B1').select

the program works fine in Word 2003 but still crashes in Word 2010.

What is the correct code for Word 2010 to 'go to' the bookmark?

like image 614
No'am Newman Avatar asked May 06 '11 15:05

No'am Newman


1 Answers

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 immediatly. 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 load
while wrdapp.Templates.Count = 0 do
  Sleep(200);

//continue operations

PS: I don't have Delphi available here, so the code may contain errors, but you get the idea

like image 180
The_Fox Avatar answered Oct 09 '22 07:10

The_Fox