Setting up Word Events from VB

P

Phillip

Hi,

I am starting the Word application in Visual Basic.
I want my Visual Basic routine to be called when the user
closes the document in Word.

I am expecting that when the user closes test.doc then the
routine myword_close should be run.

But it does not work!

Please tell me how I should proceed.

Thanks in advance for any help.

Phillip
===========================================================
============
Public mydoc As Document
Public myword As Word.Application

Sub start_editor()

' Start word
On Error GoTo wordprob
Set myword = CreateObject("Word.Application")
If myword Is Nothing Then
MsgBox "Could not start word"
Exit Sub
End If
On Error GoTo 0

' Open the document
Set mydoc = myword.Documents.Open("c:\TEMP\TEST.DOC")
myword.Visible = True

Exit Sub

wordprob:
MsgBox "Could not start Word " & Err.Description
Exit Sub
End Sub

'
' --- Event handler for Close
'
Sub myword_Close()
MsgBox "Close called"
End Sub
 
J

Jezebel

You need to declare your reference to Word in an object module (class or
form) and use the WithEvents keyword.

Private WithEvents mWordApp as Word.Application
Private WithEvents mWordDoc as Word.Document

Having done that you'll find that the left-hand listbox of the module window
now includes mWordApp and mWordDoc -- select one of those and the right-hand
listbox will list the available events for the object.


Separately, since you are using early binding (which you have to do to trap
events), you should not use CreateObject to instantiate the reference.
Better is:

Set mWordApp = new Word.Application
 

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