How Do I Tell Whether New Document Created by User or Code?

H

Henninger5

I have a Word 2003 template. I have VBA code that runs after a
Document_New() event. How can I have a check in that code for whether
the event was triggered by a user double clicking the template in
explorer (thus creating a new document from the template) or whether
the event was triggered by VBA code from somewhere else creating the
new document with the WordApp.Documents.Add() method?


Thank you.
 
T

Tony Jollans

I don't think you can tell the two apart in that event. If you want something special done (or not done) when fired from VBA you will need to set a flag somewhere.
 
H

Henninger5

I don't think you can tell the two apart in that event. If you want something special done (or not done) when fired from VBA you will need to set a flag somewhere.

--
Enjoy,
Tony

 www.WordArticles.com

Thank you for your response!

I expected as much actually. My next question becomes:

If I use VBA in the code behind an Excel Workbook to create a new Word
document from a template, how can I set a flag within the Excel VBA
that can be checked from within the Word NewDocument() event handling
code in the new Word document?
 
T

Tony Jollans

As you don't have access to the new document you must use another vector. You could create, or populate, a file on disk somewhere, or write a registry entry, or perhaps use a custom property in Word's Normal Template. Any, or all, of these are subject to outside interference, deliberately or accidentally, in theory. My preference would be a registry entry but you could do something along these lines, quite simply:

In Excel:

word-application-reference.NormalTemplate.CustomDocumentProperties.Add _
"SomeUniqueName", False, msoPropertyTypeString, Value:="SomeUnique String"
word-application-reference.Documents.Add template, etc.

In Document_New in Word:

If NormalTemplate.CustomDocumentProperties("YourUniqueName") = "YourUnique String" Then
' whatever from Excel
NormalTemplate.CustomDocumentProperties("YourUniqueName").Delete
Else
' whatever normally
End If

You would need to have an error trap to catch when the property didn't exist, and well-behaved code would ensure that the Normal Template was not flagged as changed as a result of this (save and restore the .Saved property around your code).
 

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