To create a Word document from a template with VBA, call Word’s Documents.Add method with the template’s full file path, replace any placeholder text, and save the new document under a different name. From Excel VBA on Windows, you can automate Word with CreateObject("Word.Application"); the example below creates a document from a template and saves it as a .docx file.
What creating a document from a template does
A Word template is a starting point, not usually the finished document. It can contain page layouts, styles, headers and footers, tables, logos, and placeholder text. When VBA creates a document from it, Word makes a new document based on that template. The template remains available for future documents, while the new file can be filled in and saved separately.
In Word’s object model, the key operation is Documents.Add. Its template argument identifies the template file; the call returns a Document object that your macro can edit. This is different from opening the template itself with Documents.Open, which opens the template file for editing and risks changing the source.
This approach is useful when a spreadsheet or another Office document contains data that needs to be turned into a consistently formatted letter, report, certificate, or form. It also works when the macro is stored in Word itself: the automation logic changes depending on where the macro runs, but the document-creation idea is the same.
Prepare the template and placeholders
Save the source as a Word template, commonly .dotx for a template without VBA or .dotm for a macro-enabled template. Give it a stable location and decide how the macro will identify information to fill in. For a simple example, put unique tokens such as [[CustomerName]] and [[ReportDate]] in the template. Unique markers are easier to find reliably than generic words that might occur in normal text.
- Keep the template’s formatting in Word. Apply styles to the placeholder paragraphs or table cells so replaced text inherits the intended appearance.
- Use distinct tokens and check that each one appears where expected. A token should not also appear in unrelated instructions or boilerplate.
- Store the template and output in separate locations, or at least use different filenames. A generated document should not overwrite the template.
- If placeholders are in headers, footers, text boxes, or shapes, plan to search those areas separately. A search of the main document text does not necessarily cover every Word story or object.
For a larger document-generation system, Word content controls or bookmarks can be more structured than plain text tokens. They take more setup, but make it easier to target a particular field without accidentally replacing matching text elsewhere.
Example: create and fill a Word document
The following example is intended for Excel VBA on Windows. Change the two paths and the sample values to suit your files. In the VBA editor, insert a standard module and place the code there. It uses late binding, so it does not require setting a Microsoft Word object-library reference. The numeric Word constants are included in the code for that reason.
Option Explicit
Sub CreateWordDocumentFromTemplate()
Const wdReplaceAll As Long = 2
Const wdDoNotSaveChanges As Long = 0
Const wdFormatXMLDocument As Long = 12
Dim wordApp As Object
Dim wordDoc As Object
Dim templatePath As String
Dim outputPath As String
Dim customerName As String
Dim reportDate As String
On Error GoTo CleanFail
' Set these paths and values for your files.
templatePath = "C:\Reports\ReportTemplate.dotx"
outputPath = "C:\Reports\CustomerReport.docx"
customerName = "Northwind Traders"
reportDate = Format$(Date, "mmmm d, yyyy")
If Dir$(templatePath) = vbNullString Then
Err.Raise vbObjectError + 1000, , "Template file was not found."
End If
If Dir$(outputPath) <> vbNullString Then
Err.Raise vbObjectError + 1001, , "Output file already exists."
End If
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True
' Create a new document based on the template.
Set wordDoc = wordApp.Documents.Add(templatePath, False, 0, True)
' Replace every matching token in the document's main text story.
With wordDoc.Content.Find
.Text = "[[CustomerName]]"
.Replacement.Text = customerName
.Forward = True
.Wrap = 1
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.Execute , , , , , , , , , , wdReplaceAll
End With
With wordDoc.Content.Find
.Text = "[[ReportDate]]"
.Replacement.Text = reportDate
.Forward = True
.Wrap = 1
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.Execute , , , , , , , , , , wdReplaceAll
End With
' Save as a standard Word document (.docx).
wordDoc.SaveAs2 outputPath, wdFormatXMLDocument
wordDoc.Close wdDoNotSaveChanges
wordApp.Quit
Set wordDoc = Nothing
Set wordApp = Nothing
MsgBox "Created: " & outputPath, vbInformation
Exit Sub
CleanFail:
On Error Resume Next
If Not wordDoc Is Nothing Then wordDoc.Close wdDoNotSaveChanges
If Not wordApp Is Nothing Then wordApp.Quit
Set wordDoc = Nothing
Set wordApp = Nothing
MsgBox "Could not create the document: " & Err.Description, vbExclamation
End Sub
The macro checks that the template exists and refuses to overwrite an existing output file. The four positional arguments to Documents.Add are the template path, whether to create a new template, the document type, and whether the new document should be visible. The replacement calls use Word’s Find object to replace all instances of each token in the main text story. The date is formatted as readable text before it is inserted.
The example assumes the output folder already exists. It also leaves Word visible while the macro runs, which is helpful for checking the result. To run it unattended, you can set wordApp.Visible = False, but add suitable error logging and test the output before relying on a background process.
Run it from Excel or Word
In Excel for Microsoft 365 on Windows, open the VBA editor with Alt+F11, add the macro to a standard module, and run it with the cursor inside the procedure by pressing F5. You can also use Excel’s Developer tab and Macros command to run a saved macro. If the Developer tab is hidden, enable it through File > Options > Customize Ribbon.
If the code is stored in Word rather than Excel, you can use Word’s VBA editor and run it there. A Word-hosted macro can refer directly to Word’s document objects, so it does not need to start a separate Word application. The sample is specifically written for Excel automation, however; do not paste it into Word unchanged and expect its application-creation and cleanup logic to be the best design for that situation.
On Mac, VBA and Word automation are available, but Windows-specific automation details and file paths do not transfer directly. The Windows example uses CreateObject("Word.Application") and paths such as C:\Reports\; Mac installations, permissions, and path conventions differ, and automation support can depend on the Office build. Use Mac-appropriate paths and verify that the needed Word automation calls work in the installed version. The Windows shortcut Alt+F11 also differs on Mac; use the Visual Basic Editor command available in the Mac Office menus or keyboard-shortcut settings.
Choose the right template and output format
Use a .dotx template when the template itself does not need to contain VBA. Use .dotm when the template includes macros. In either case, a typical generated document can be saved as .docx. The example uses Word’s wdFormatXMLDocument value, 12, for that format. If the generated file itself must contain VBA, save it in a macro-enabled document format instead and make sure that is genuinely required; a .docx cannot store document macros.
Think about where generated files should go and how filenames are assigned. A fixed output filename is easy to understand but will stop the macro when that file already exists, as the example does. For batches, build each filename from a unique record identifier, check for collisions, and avoid using untrusted text as a path without validating it. Also consider whether the document should stay open for review or close after saving.
If the template contains a header or footer token, the sample’s wordDoc.Content.Find calls may leave it untouched because they search the main document story. Search the relevant header or footer ranges explicitly, including each section where the content differs. Tables in the main body are generally part of that main story, but floating text boxes and other shapes can require separate handling.
Common problems and how to solve them
- Word is not installed or cannot start: Excel cannot automate Word if the desktop Word application is unavailable or its installation is damaged. Confirm that Word opens normally and that Office is correctly installed.
- The template is not found: Check the complete path, spelling, extension, and access permissions. A path that works on one computer may not exist on another; consider storing it in a known shared location or building it from a configured folder.
- The macro stops at SaveAs2: Confirm that the output folder exists and is writable, and that the file is not already open or locked. The example deliberately refuses an existing output name to avoid an accidental overwrite.
- A placeholder remains: Check exact spelling, brackets, and capitalization. Also check whether the token is in a header, footer, shape, or other story outside the search range.
- Word is left running: Close both the created document and the Word application object when finished. If an error occurs, the error handler attempts to close them without saving further changes.
- Replacement text is altered unexpectedly: Word Find-and-Replace treats certain characters, such as special replacement codes, as instructions. If input may contain those characters, test carefully or use content controls or bookmarks and assign their contents directly.
During development, keep Word visible and inspect the result before changing the macro to run invisibly. A search-and-replace operation that completes without an error does not prove that every intended token was found; for critical documents, count expected tokens or validate required fields before saving.
Security and reliability considerations
Only run VBA from a workbook or document you trust. Office macro security settings can block code, and lowering those protections globally is not a good workaround. Follow your organization’s approved process for trusted files and signed macros. If the macro processes external data, validate that data before putting it into a document, particularly if it can affect filenames or Word replacement behavior.
Save a copy of the workbook before running a macro that creates or changes files. VBA macros cannot be undone with Ctrl+Z, and a faulty batch process can create many incorrect documents before anyone notices. For important output, test with a copy of the template and a small sample, then verify the saved documents and the original template separately.
Alternatives to VBA automation
For occasional documents, opening a template manually and filling it in may be simpler and less fragile than maintaining a macro. For repeatable Office workflows, Power Automate may be appropriate where the organization’s Microsoft 365 licensing, connectors, and document storage support the required actions. Mail merge in Word is another option for generating many similar letters from a data source; it can be easier to maintain when the task is primarily inserting records into a standard letter layout.
VBA is a good fit when the process already runs in desktop Excel or Word and needs custom decisions, validation, or interaction with other Office data. Choose it when those benefits justify maintaining code, handling errors, and testing changes to the template. For straightforward one-time output, a manual template or mail merge may involve less setup.
Frequently Asked Questions
Can Excel VBA create a Word document from a .dotx template?
Yes. Use Word automation to call Documents.Add with the .dotx file’s full path. Word creates a new document based on the template, which the macro can fill and save as a separate .docx.
What is the difference between Documents.Add and Documents.Open?Documents.Add creates a new document based on a template. Documents.Open opens an existing file, including a template, for editing. For generating output while preserving the source template, use Documents.Add.
Do I need to set a Word reference in Excel VBA?
Not for the late-binding example above, which declares Word objects as Object and starts Word with CreateObject. Early binding is another option: add the Microsoft Word Object Library reference in the VBA editor, then declare Word-specific object types and constants. The reference can make Word’s methods easier to browse, but it needs to be available on the machine running the macro.
Can the macro replace text in a Word header or footer?
Yes, but search the appropriate header or footer ranges rather than relying only on wordDoc.Content. Documents can have different first-page, odd-page, or section headers, so inspect the template structure and cover the relevant ranges.
Can I save the generated file as a PDF?
Yes. Word supports exporting a document to PDF, but the example saves a .docx. Add a separate PDF export step using Word’s document export methods if PDF is the required deliverable, and keep the editable document too if users will need to revise it.
Related
- IF Rules in Google Sheets: How Formulas and Rules Work
- Inventory Spreadsheet in Google Sheets or Google Docs?
- Google Sheets Inventory Spreadsheet: Setup and Tips
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA AutoFilter: Examples, Criteria, and FixesExcel VBA AutoFilter filters a worksheet range or Excel table by applying criteria to one or more columns.…
- VBA Range Sum: Methods, Examples, and Common ErrorsTo sum a range in Excel VBA, use Application.WorksheetFunction.Sum and assign its result to a variable or cell.…
- Set Image Height in Excel VBA Using InchesTo set an image to a height measured in inches, assign its VBA Height property the result of…
- Move a Picture in an Excel UserForm with the MouseTo move a picture around an Excel UserForm with the mouse, handle the Image control’s MouseDown and MouseMove…
- Access VBA Find in String: InStr, Options, and ExamplesIn Access VBA, use InStr to find one string inside another: it returns the 1-based position of the…
- VBA Loop Format: Syntax, Examples, and When to Use EachA VBA loop repeats a block of code while counting through values, visiting items in a collection, or…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.