1

Is this a Word 2003 VBA bug? DocumentBeforePrint executes multiple times?

I reference

http://msdn.microsoft.com/en-us/library/office/aa211873(v=office.11).aspx

http://msdn.microsoft.com/en-us/library/office/aa211915(v=office.11).aspx

DocumentBeforeClose syntax

I make a test.dot with macro DocumentBeforePrint.

'ref http://msdn.microsoft.com/en-us/library/office/aa211915(v=office.11).aspx
Dim X As New EventClassModule

Sub Register_Event_Handler()
Set X.appWord = Word.Application
End Sub

Private Sub Document_New()
   Call Register_Event_Handler
End Sub

Private Sub Document_Open()
   Call Register_Event_Handler
End Sub


'ref http://msdn.microsoft.com/en-us/library/office/aa211873(v=office.11).aspx

Public WithEvents appWord As Word.Application

Private Sub appWord_DocumentBeforePrint _
    (ByVal Doc As Document, _
    Cancel As Boolean)

    MsgBox "WORKING!"
End Sub

When I press Ctrl+P, the macro executes.

There is a bug. When I double click test.dot to generate two word files (a.doc/b.doc).

Press Ctrl+P,the DocumentBeforePrint will execute twice.

If I generate 3 word files, Press Ctrl+P, the Macro will execute three times.

What's wrong? I just want to execude once.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
Eigen
  • 13
  • 2
  • You don't provide enough accurate information: I assume the code you do give us is not all in the same module? Please separate it and indicate in what modules the various procedures are located. – Cindy Meister May 30 '18 at 09:54
  • I upload the test file to google drive .https://drive.google.com/open?id=1aCwSQY4TCWWsU73fLVuNdloy22H3XW-m – Eigen May 30 '18 at 14:34
  • I'm not going to download your document that contains macros. Please use the [edit] link to amend your original question with the information about in which modules the various procedures are stored - they certainly are not all in one module? – Cindy Meister May 30 '18 at 16:24
  • See my edited answer, and you'll understand why I asked my original question. – Cindy Meister May 30 '18 at 16:48

1 Answers1

0

It appears you have put all the code except the printing code in the ThisDocument code module. This is incorrect. Because you put ^Dim X as NewEventClassModuleinThisDocument`, which is, itself, a class module representing each document, multiple instances were being created. Declaring it in a "plain module" doesn't cause this problem.

You need three modules:

"Plain" module:

Dim X As New EventClassModule

Sub Register_Event_Handler()
  Set X.appWord = Word.Application
End Sub

"ThisDocument" module:

Private Sub Document_New()
   Register_Event_Handler
End Sub

Private Sub Document_Open()
   Register_Event_Handler
End Sub

"EventClassModule"

Public WithEvents appWord As Word.Application

Private Sub appWord_DocumentBeforePrint _
    (ByVal Doc As Document, _
    Cancel As Boolean)

    MsgBox "WORKING!"
End Sub
Cindy Meister
  • 25,071
  • 21
  • 34
  • 43