File never prints (VBA)

A

Alan

I am trying to print a file from VBA with the code found below.
What happens is that the printer monitor shows it as "Spooling", and
when I go to Word, where the file is open, it says "Please wait while
word finishes all pending print jobs." The file contains one word of
text, and it never prints.

The last thing shown in Debug is: "Closing document . . ."

What am I doing wrong? Thanks, Alan

Private Sub CreatePdfDocs()
Dim Word As Word.Application
Dim aWordFileName As String, i As Integer

Set Word = New Word.Application

On Error GoTo Finally

aWordFileName = "C:\Users\Alan\Desktop\Test.doc"
' Open a Word document
Debug.Print "Opening document . . . "
Word.Documents.Open Filename:=aWordFileName, Visible:=True

' Print it to PDF
Debug.Print "Printing . . ."
Word.Documents(aWordFileName).PrintOut To:="HP Deskjet D4200
series"

Debug.Print "Closing document . . ."
Word.Documents.Close SaveChanges:=False
Word.Quit
Set Word = Nothing
Exit Sub
Finally:
MsgBox "An error occurred" & vbCrLf & Err.Source & vbCrLf & _
"Error # " & Err.Number & ": " & Err.Description,
vbCritical
Word.Quit
Set Word = Nothing
End Sub
 
A

Alan

Never mind. I added a check of
Word.Application.BackgroundPrintingStatus before closing, like this:

Do While Word.Application.BackgroundPrintingStatus
DoEvents
Loop
 
J

Jay Freedman

Hi Alan,

I see in your other post that you found one way to solve this problem, by
looping until printing finishes. However, there's another, better way.

The PrintOut method has an optional argument named Background. Its default value
is True, which means that printing occurs in the background and allows the macro
to continue executing. The problem with letting it do that is that your macro
immediately closes the document, so spooling never finishes. If you set
Background to False, the macro can't execute any more instructions until the
spooling is done. So change the statement to

Word.Documents(aWordFileName).PrintOut To:="HP Deskjet D4200 series", _
Background:=False

--
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