0
votes

In a VSTO addin for Word 16 (32) on a Windows 10, I keep track of each document for Ribbon purposes.

I am using the VSTO Designer's Application object. In the designer it looks like this;

Friend WithEvents Application As Microsoft.Office.Interop.Word.Application

Then in ThisAddinn I have the standard code for a WithEvents object.

 Private Sub Application_NewDocument(Doc As Microsoft.Office.Interop.Word.Document) Handles Application.NewDocument

 End Sub

In ThisAddin I also handle Application.DocumentOpen

After the first instance of Word is open if a user right clicks on the Word icon in the task bar and chooses Word then a new Word document is created, however the above 2 events do not fire.

I also wanted to point out that opening a document from the Word interface or clicking on a word.docx file and opening it all work. It is only when you open a new instance of work by right clicking on the word icon in the task bar.

What event do I need?

I do see that Application.WindowActivate fires. Do I need to use this?

1
Where and when do you subscribe to the events in the code?Eugene Astafiev
Question updated. I am using the VSTO designer's application withevents object.darbid
At startup, you can check whether any document is opened and simulate the DocumentOpen event fired. It seems that events can be fired before you subscribe to them.Eugene Astafiev
At start up I do check for open documents. The problem is that when you start a second word document from the task bar startup does not fire either.darbid

1 Answers

0
votes

The Application.NewDocument event is fired when a new document is created. If you are working with a document embedded within another document, this event will not occur. You may try to use the following VBA macro to make sure events are fired:

Public WithEvents appWord as Word.Application 

Private Sub appWord_NewDocument(ByVal Doc As Document) 
 Dim intResponse As Integer 
 Dim strName As String 
 Dim docLoop As Document 

 intResponse = MsgBox("Save all other documents?", vbYesNo) 

 If intResponse = vbYes Then 
 strName = ActiveDocument.Name 
 For Each docLoop In Documents 
 With docLoop 
 If .Name <> strName Then 
 .Save 
 End If 
 End With 
 Next docLoop 
 End If 
End Sub

The Application.DocumentOpen event is fired when a document is opened.

Public WithEvents appWord as Word.Application 

Private Sub appWord_DocumentOpen(ByVal Doc As Document) 
 Dim intResponse As Integer 
 Dim strName As String 
 Dim docLoop As Document 

 intResponse = MsgBox("Save all other documents?", vbYesNo) 

 If intResponse = vbYes Then 
 strName = ActiveDocument.Name 
 For Each docLoop In Documents 
 With docLoop 
 If .Name <> strName Then 
 .Save 
 End If 
 End With 
 Next docLoop 
 End If 
End Sub

At startup, you can check whether any document is opened and simulate the DocumentOpen event fired. It seems that events can be fired before you subscribe to them.