1

I am trying to write a macro which uses the Word objects to create a Word document based on a Word template document.

I am having some difficulties when I use Option Explicit. Without it I can just omit the Dim ... line but I would like that there.

Here is the code so far:

Option Explicit
Sub PopulateWordDoc()
    Dim wApp As Object
    Set wApp = CreateObject("Word.Application")
    Dim wdDoc As Word.Document ' User-defined type not defined error on this line
    Set wDoc = wApp.Documents.Open("C:\path\WordTestTemplateDoc.dotx", ReadOnly:=False)

    With wDoc
        .Content.Find.Execute FindText:="<Project ID>", ReplaceWith:="This is the project id....."
        .SaveAs2 Filename:=("C:\path\NewWordDoc.docx"), FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False
    End With

End Sub

1
  • What you want is called "early binding". What you are currently doing is "late binding". The complete article can be found here: support.microsoft.com/en-us/kb/245115 Commented Apr 22, 2016 at 17:53

2 Answers 2

2

Add a reference in the VBE to Microsoft Word xx.0 Object Library as described in this article:

https://msdn.microsoft.com/en-us/library/office/gg264402.aspx

Afterwards, the VBE will even offer auto-completion as it does when you write code for Excel.

Sign up to request clarification or add additional context in comments.

Comments

0

OptionExplicit makes it so that you ABSOLUTELY MUST declare everything you use. By not adding the statement, you tell the VB compiler that it is in control of determining the types of variables that were never declared. This is somewhat lazy and could lead to potential problems. You should always declare all your variables.

1 Comment

Which is why I want to

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.