2

I'm working with a class that manipulates several Word documents. My intention is to keep references to the Word documents and have them up to date by calling an update method from the template document event methods Open() and Close(), passing a reference to the opened or closed document, like this:

' inside the template's ThisDocument code:
Private Sub Document_Open()
    Call Session.UpdateOpened(ThisDocument)
End Sub

The problem is that ThisDocument refers to the template document, not the actual document that triggers the event, so I had to change ThisDocument to ActiveDocument:

Private Sub Document_Open()
    Call Session.UpdateOpened(ActiveDocument)
End Sub

This should work provided that the events in the template are called from an active document, but is this always the case? And in any case, the question remains:

Is there a way to refer to the actual document from the template code?

FOLLOW-UP: I've seen this question ThisDocument object reference refers to the same issue. The underlying problem is probably one of design so it might never get a straightforward answer. See the comments below for some useful tips.

Eklektikos
  • 21
  • 4
  • 2
    Presumably the "class that manipulates several Word documents" is in a global template? Have you considered creating an application event handler instead of using the events in the template's `ThisDocument` module? The application events, `DocumentOpen` and `DocumentBeforeClose`, both pass the document that triggered the event. – Timothy Rylatt Apr 19 '22 at 14:17
  • Yes, it is the Normal template. So I understand that there is no simple way to refer to the actual triggering document from the template, and that application events are the proper approach in this case. I will try that. Thank you for the tip! – Eklektikos Apr 19 '22 at 14:29
  • 2
    Do not use the Normal template for your code. Word will occasionally decide it has become corrupt and replace it, deleting all your code in the process. The proper place for code is in a template placed into the Startup folder. See File | Options | Advanced | General | File Locations to find the location where Word is looking for startup files. – Timothy Rylatt Apr 19 '22 at 14:36
  • Well that is good to know! It felt like a temporary location for my code but wouldn't have expected it to be a dangerous one. Thanks again! – Eklektikos Apr 19 '22 at 14:50
  • 1
    As you open a document to process, assign it to a variable object like oDoc. `Set oDoc = Application.Documents.Open("document name")` and process oDoc rather than ActiveDocument or ThisDocument. – Charles Kenyon Apr 19 '22 at 16:10

0 Answers0