Word Automation

G

Guest

I ran the below program in a machine with XP SP1 and Word 2000 it took only 2
or 3 seconds to insert the bookmarks into the word document. But in a machine
with XP SP2 and Word 2000 it took 18 seconds in an average. I am using the
similar kind of program to insert the bookmarks into a letter at the runtime.

Could anyone please help me out.

Private Sub Command1_Click()
On Error GoTo err
Dim obj As New Word.Application
Dim bk As Bookmark
obj.Documents.Open "C:\Test\ObjA.dot"
obj.Visible = True
StartLog
SendToLog ("BookMark Insertion Starts")
For Each bk In obj.ActiveDocument.Bookmarks
If obj.ActiveDocument.Bookmarks.Exists(bk.Name) Then
obj.ActiveDocument.GoTo What:=wdGoToBookmark, Name:=bk.Name
obj.ActiveDocument.Bookmarks(bk.Name).Select
obj.Selection.InsertAfter bk.Name
obj.ActiveDocument.Bookmarks(bk.Name).Delete
End If
Next
SendToLog ("BookMark Insertion Ends")
EndLog
MsgBox "completed"

err:
Set obj = Nothing

End sub
 
J

Jay Freedman

Try eliminating the selection and using just the bookmark's range:

For Each bk In obj.ActiveDocument.Bookmarks
obj.ActiveDocument.Bookmarks(bk.Name).Range.Text = bk.Name
Next

The selection isn't necessary, and it often forces Word to redraw the
screen, which is by far the slowest operation in the macro. Also, it isn't
necessary to test whether the bookmark exists -- if it didn't exist, the For
Each loop wouldn't iterate it.

As for your original question -- which I assume was "why is there a
difference between SP1 and SP2?" -- I don't know. This change should make
the program enough faster that it doesn't matter.

If you have any further questions, please post in one of the word.vba
newsgroups, not in docmanagement.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 
J

Jay Freedman

Taking a second look at this, the code can be even further condensed
-- there's no need to work with the bookmark's name as an index into
the Bookmarks collection once you have a pointer to the bookmark
object itself:

For Each bk In obj.ActiveDocument.Bookmarks
bk.Range.Text = bk.Name
Next

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top