View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
Dick Kusleika[_4_] Dick Kusleika[_4_] is offline
external usenet poster
 
Posts: 595
Default Help required with code - Automation Error ......... Ooops - Here's the code

JRB

Just guessing, but I'll bet that the MailMerge isn't fully executed by the
time you get to Set WD = Nothing. And that open process is not allowing you
to destroy the WD object. Those DDE links can be slow. I couldn't see any
property of the MailMerge object that you could check to see when it's
complete.

One klunky workaround that I can think of is to merge it to a new document
instead of a printer. Then you can check the name of the new document to
determine when it's complete

Dim wdDoc as Object

Set wdDoc = WD.Documents.Open(...)

With wdDoc
...
Do
DoEvents
Loop Until ActiveDocument.Name < wdDoc.Name

ActiveDocument.PrintOut
End With

I don't know if that will work. The ActiveDocument test may pass before the
merge is complete. You might post a question in one of the Word groups (I
think there's one for mailmerges) and see if they have any bright ideas.
All this is predicated on the assumption that I'm right about the merge
process not finishing before you kill your objects.

You might start by testing that theory. How long does it take to start
printing? If it's, say, 10 seconds, then you could stick a loop in there
like

Dim dNow as Date

dNow = Now

Do
DoEvents
Loop Until (Now-TimeSerial(0,0,10)) dNow

Then kill the word object. If you can run it again without an error, then I
think it's pretty clear that merge is holding that object open.

Good luck, and let me know if you find a satisfactory answer.

--
Dick Kusleika
MVP - Excel
Excel Blog - Daily Dose of Excel
www.dicks-blog.com

"JRB" wrote in message
...
Here is the code I omitted to send

Sub MailMergeTest()

Dim WD As Object
Set WD = CreateObject("Word.Application")
WD.Application.DisplayAlerts = wdAlertsNone
WD.Documents.Open (ThisWorkbook.Path & "\PrivList Labels.doc")

With ActiveDocument 'THIS LINE PRODUCES AUTOMATION ERROR IF RUN
TWICE
With .MailMerge
If .State < wdMainAndDataSource Then
.OpenDataSource _
Name:=ThisWorkbook.Path & "\PrivList.csv", _
LinkToSource:=True
End If
.Destination = wdSendToPrinter
.Execute
End With
.Close SaveChanges:=wdDoNotSaveChanges
End With

WD.Application.DisplayAlerts = wdAlertsAll
WD.Application.EnableEvents = True
WD.Quit SaveChanges:=wdDoNotSaveChanges
Set WD = Nothing

End Sub