Set Reference to Word Template in VBA

Hi all,

I am looking to find the most efficient/simplest way to reference a newly added Word template object. My code is as follows:

    Dim appWord As Word.Application
    Set appWord = CreateObject("Word.Application")
    appWord.Visible = True
    appWord.Documents.Add Template:= _
        "H:\Documents\Misc Assignments\Template.dotx" _
        , NewTemplate:=False, DocumentType:=0

I wan to do something similar to:

Set objWord = appWord.Documents.Add

How would I do this with templates as there is already an "="? Can I avoid using ActiveDocument?

Thanks

Answer
Answer

I think you may have confused me as much as you confused yourself. <grin>

First, let's understand what happens when you execute the Documents.Add statement in your code snippet.

The part Template:="H:\..." is an argument (that is, a value passed to the Add method), just like the two arguments NewTemplate and DocumentType. It is not an assignment, just an argument. Note that argument values follow the := operator, which is not the same as the assignment = operator.

The Add method causes Word to create a new document based on the template in the argument.

I think that what you're asking is how to get a variable to hold the resulting document (which is not a reference to a template). In that case, after declaring the variable

   Dim docWord As Word.Document

you can assign the return value of the Add method to that variable as follows:

   Set docWord = appWord.Documents.Add(Template:= _

        "H:\Documents\Misc Assignments\Template.dotx" _
        , NewTemplate:=False, DocumentType:=0)

When a method returns a value and you want to assign that value to a variable, VBA requires you to enclose the list of arguments in parentheses. There's no good reason for that, but you'll get a compile error if you omit the parentheses.

_____________________________
https://jay-freedman.info

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated October 5, 2021 Views 1,327 Applies to: