Fixes & Troubleshooting

Fix: Word Template Placeholders Not Replacing Correctly from Excel

Fix replacement failures by treating every Word placeholder as a literal contract. Match Excel headers exactly, inspect every relevant Word story, reject ambiguous source text, and verify that no token remains before a DOCX becomes final.

Exact {{Tag}} contract
Header preflight
All Word stories
Leftover-tag gate
A successful Find in the main body does not prove that headers, footers, or text boxes were processed.

Quick answer: verify the contract before replacing any text

Template side

Use one literal pattern such as {{ClientName}}. Inventory the tags in the main story, headers, footers, and linked text frames before generating a document.

Excel side

Use ClientName as the exact mapped header and store document-ready text beneath it. Reject duplicate headers, malformed names, Excel errors, and ambiguous values.

Stop on mismatch

Do not save a final file when Excel maps a missing token, Word contains an unknown token, or any {{...}} marker remains after replacement.

Diagnose six common placeholder failures

Wrong braces or case

{ClientName}, {{ClientName}}, and {{clientname}} are different literal strings when matching is case-sensitive.

Spaces inside the tag

{{ ClientName }} does not match {{ClientName}}. Retype the tag or adopt one documented spacing rule.

Header spelling differs

An Excel header such as Client Name cannot silently map to {{ClientName}}. Use an explicit mapping or make the names identical.

Tag lives outside the body

A macro that searches only Document.Content can miss a header, footer, or text-frame story.

Replacement text is unsafe

Tabs, paragraph marks, placeholder braces, or Excel errors can change document structure or create a new leftover token.

No final verification

The document is saved even though one mapped tag was absent or an unknown template tag remained.

Define one literal placeholder contract

A — DocumentID

A stable text identifier for audit and error messages. Format IDs as Text before entering values when leading zeros matter.

B — OutputName

A unique Windows-safe filename stem without .docx. The helper rejects duplicates, reserved names, and existing outputs.

C onward — mapped fields

Every header becomes one exact token. Header ClientName maps to {{ClientName}}.

Allowed header characters

Use letters, digits, and underscore only. This removes hidden spaces and punctuation ambiguity from tag names.

Document-ready values

Store the exact text Word should receive. Do not expect number formatting alone to turn 0.285 into 28.5%.

Contiguous rows

Keep one record per row without blank gaps inside the table. The helper stops on a blank internal row instead of guessing intent.

Required local structure

Save the workbook as .xlsm. Put the template at Templates\PlaceholderTemplate.docx. The helper creates or uses GeneratedDocuments\ beside the workbook.

Search the Word locations where tags actually live

StoryRanges

Word exposes separate stories for the main text and available headers, footers, notes, and text-frame content.

NextStoryRange

A header or footer story can continue through later sections. Linked text boxes can also form a chain.

Range-based Find

A Find operation on a Range redefines that Range without moving the user’s Selection, which suits background automation.

Fresh document per row

Create every output from the original template. Never reuse a document that already contains another row’s values.

Official references: Word Document.StoryRanges, Range.NextStoryRange, Find object, and Documents.Add.

Complete the preflight before Word generates row 2

1. Validate headers

Reject blanks, duplicates, invalid characters, and an incorrect A/B column order.

2. Validate every row

Check IDs, output names, Excel errors, control characters, placeholder braces, and existing files.

3. Inventory the template

Collect every {{...}} token from all available Word stories before generation.

4. Compare both directions

Every mapped Excel token must exist in Word, and every Word token must have one Excel header.

5. Generate to a temporary file

Save inside the final folder under a run-specific temporary name, verify it, then rename it without overwriting.

6. Scan the finished document

Block the output when any opening {{ still appears in a Word story.

Free VBA helper: verify and replace literal tags

This Excel VBA example generates DOCX files only. It uses one standard Word template, reads document-ready text from Excel, searches all available Word stories, and stops on a contract failure.

Full preflight first

No Word output starts until all Excel rows, names, mapped fields, and existing files pass validation.

Exact and case-sensitive

{{ClientName}} is replaced only by the exact mapped token. The code does not guess synonyms.

Temporary-file ownership

On failure the handler deletes only the current run’s temporary DOCX, never a pre-existing final file.

Honest scope

The helper rejects multiline text and tokens overlapping fields or inline objects. It does not export PDF or validate final layout. Existence checks are not a multi-process lock for a shared output folder.

Excel VBA — verified Word placeholder replacementStatic text tags • DOCX output
Option Explicit

Private Const DATA_SHEET As String = "Data"
Private Const TEMPLATE_FOLDER As String = "\Templates"
Private Const OUTPUT_FOLDER As String = "\GeneratedDocuments"
Private Const TEMPLATE_FILE As String = "PlaceholderTemplate.docx"
Private Const FIRST_DATA_ROW As Long = 2

Private Const HEADER_DOCUMENT_ID As String = "DocumentID"
Private Const HEADER_OUTPUT_NAME As String = "OutputName"
Private Const TOKEN_OPEN As String = "{{"
Private Const TOKEN_CLOSE As String = "}}"

Private Const WD_FIND_STOP As Long = 0
Private Const WD_COLLAPSE_END As Long = 0
Private Const WD_DO_NOT_SAVE_CHANGES As Long = 0
Private Const WD_ALERTS_NONE As Long = 0
Private Const FILE_ATTRIBUTES As Long = 39

Public Sub GenerateDocumentsWithVerifiedPlaceholders()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim lastCell As Range
    Dim lastRow As Long
    Dim lastColumn As Long
    Dim rowNumber As Long
    Dim columnNumber As Long
    Dim documentId As String
    Dim outputName As String
    Dim headerText As String
    Dim tokenText As String
    Dim replacementText As String
    Dim templatePath As String
    Dim outputFolderPath As String
    Dim finalDocxPath As String
    Dim currentTempPath As String
    Dim runId As String
    Dim replacedCount As Long
    Dim leftoverToken As String
    Dim generatedCount As Long
    Dim currentRow As Long
    Dim headerColumns As Object
    Dim mappedTokens As Object
    Dim documentIds As Object
    Dim outputNames As Object
    Dim wdApp As Object
    Dim templateDoc As Object
    Dim outputDoc As Object
    Dim errorNumber As Long
    Dim errorMessage As String
    Dim errorLocation As String
    Dim dataValues As Variant

    On Error GoTo CleanFail

    Set wb = ThisWorkbook
    If Len(wb.Path) = 0 Then
        Err.Raise vbObjectError + 2900, , _
            "Save the Excel workbook as .xlsm before running this macro."
    End If
    Set ws = RequireWorksheet(wb, DATA_SHEET)
    lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
    If lastColumn < 3 Then
        Err.Raise vbObjectError + 2901, , _
            "Data needs DocumentID, OutputName, and at least one mapped field."
    End If

    Set lastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), _
        LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious, MatchCase:=False)
    If lastCell Is Nothing Then
        Err.Raise vbObjectError + 2902, , "The Data sheet is empty."
    End If
    If lastCell.Row < FIRST_DATA_ROW Then
        Err.Raise vbObjectError + 2902, , "The Data sheet has no records."
    End If
    lastRow = lastCell.Row
    dataValues = ws.Range(ws.Cells(1, 1), _
        ws.Cells(lastRow, lastColumn)).Value2

    Set headerColumns = CreateObject("Scripting.Dictionary")
    headerColumns.CompareMode = vbTextCompare
    Set mappedTokens = CreateObject("Scripting.Dictionary")
    mappedTokens.CompareMode = vbBinaryCompare
    ValidateHeaders ws, lastColumn, headerColumns, mappedTokens

    If headerColumns(HEADER_DOCUMENT_ID) <> 1 Or _
       headerColumns(HEADER_OUTPUT_NAME) <> 2 Then
        Err.Raise vbObjectError + 2903, , _
            "Required column order is A DocumentID, B OutputName, then mapped fields."
    End If

    templatePath = wb.Path & TEMPLATE_FOLDER & "\" & TEMPLATE_FILE
    outputFolderPath = wb.Path & OUTPUT_FOLDER
    If Not FileExists(templatePath) Then
        Err.Raise vbObjectError + 2904, , _
            "Word template is missing: " & templatePath
    End If
    If Not FolderExists(outputFolderPath) Then
        MkDir outputFolderPath
    End If

    Set documentIds = CreateObject("Scripting.Dictionary")
    documentIds.CompareMode = vbTextCompare
    Set outputNames = CreateObject("Scripting.Dictionary")
    outputNames.CompareMode = vbTextCompare

    For rowNumber = FIRST_DATA_ROW To lastRow
        currentRow = rowNumber
        If RowIsBlank(ws, rowNumber, lastColumn) Then
            Err.Raise vbObjectError + 2905, , _
                "Blank row inside the Data table: row " & rowNumber
        End If

        documentId = Trim$(ReadValueText(dataValues(rowNumber, 1), _
            "DocumentID", rowNumber))
        outputName = Trim$(ReadValueText(dataValues(rowNumber, 2), _
            "OutputName", rowNumber))
        If Len(documentId) = 0 Then
            Err.Raise vbObjectError + 2906, , _
                "DocumentID is blank in row " & rowNumber
        End If
        If Len(outputName) = 0 Then
            Err.Raise vbObjectError + 2907, , _
                "OutputName is blank in row " & rowNumber
        End If
        If documentIds.Exists(documentId) Then
            Err.Raise vbObjectError + 2908, , _
                "Duplicate DocumentID in rows " & documentIds(documentId) & _
                " and " & rowNumber & ": " & documentId
        End If
        documentIds.Add documentId, rowNumber

        ValidateFileStem outputName, rowNumber
        If outputNames.Exists(outputName) Then
            Err.Raise vbObjectError + 2909, , _
                "Duplicate OutputName in rows " & outputNames(outputName) & _
                " and " & rowNumber & ": " & outputName
        End If
        outputNames.Add outputName, rowNumber
        finalDocxPath = outputFolderPath & "\" & outputName & ".docx"
        If Len(finalDocxPath) > 240 Then
            Err.Raise vbObjectError + 2910, , _
                "Output path is too long in row " & rowNumber & ": " & finalDocxPath
        End If
        If FileExists(finalDocxPath) Then
            Err.Raise vbObjectError + 2911, , _
                "Output already exists: " & finalDocxPath
        End If

        For columnNumber = 3 To lastColumn
            headerText = Trim$(CStr(ws.Cells(1, columnNumber).Value2))
            replacementText = ReadValueText(dataValues(rowNumber, columnNumber), _
                headerText, rowNumber)
            ValidateReplacementText replacementText, headerText, rowNumber
        Next columnNumber
    Next rowNumber

    currentRow = 0

    Set wdApp = CreateObject("Word.Application")
    wdApp.Visible = False
    wdApp.DisplayAlerts = WD_ALERTS_NONE
    wdApp.ScreenUpdating = False

    Set templateDoc = wdApp.Documents.Open(templatePath, False, True, False)
    ValidateTemplateContract templateDoc, mappedTokens
    templateDoc.Close WD_DO_NOT_SAVE_CHANGES
    Set templateDoc = Nothing

    runId = Format$(Now, "yymmdd_hhnnss") & "_" & CStr(Application.Hwnd)
    For rowNumber = FIRST_DATA_ROW To lastRow
        currentRow = rowNumber
        documentId = Trim$(CStr(dataValues(rowNumber, 1)))
        outputName = Trim$(CStr(dataValues(rowNumber, 2)))
        finalDocxPath = outputFolderPath & "\" & outputName & ".docx"
        currentTempPath = outputFolderPath & "\.~dfp_" & runId & _
            "_" & Format$(rowNumber, "000000") & ".docx"

        If FileExists(finalDocxPath) Then
            Err.Raise vbObjectError + 2912, , _
                "Output appeared after preflight: " & finalDocxPath
        End If
        If FileExists(currentTempPath) Then
            Err.Raise vbObjectError + 2913, , _
                "Temporary path already exists: " & currentTempPath
        End If

        Set outputDoc = wdApp.Documents.Add(templatePath, False, 0, False)
        For columnNumber = 3 To lastColumn
            headerText = Trim$(CStr(ws.Cells(1, columnNumber).Value2))
            tokenText = TOKEN_OPEN & headerText & TOKEN_CLOSE
            replacementText = CStr(dataValues(rowNumber, columnNumber))
            replacedCount = ReplaceTokenInAllStories( _
                outputDoc, tokenText, replacementText)
            If replacedCount = 0 Then
                Err.Raise vbObjectError + 2914, , _
                    "Mapped token was not found while generating row " & _
                    rowNumber & ": " & tokenText
            End If
        Next columnNumber

        leftoverToken = FirstTemplateToken(outputDoc)
        If Len(leftoverToken) > 0 Then
            Err.Raise vbObjectError + 2915, , _
                "Unreplaced token remains in row " & rowNumber & _
                ": " & leftoverToken
        End If

        outputDoc.SaveAs2 currentTempPath
        outputDoc.Close WD_DO_NOT_SAVE_CHANGES
        Set outputDoc = Nothing
        If Not FileExists(currentTempPath) Then
            Err.Raise vbObjectError + 2916, , _
                "Word did not create the temporary DOCX for row " & rowNumber
        End If
        If FileLen(currentTempPath) = 0 Then
            Err.Raise vbObjectError + 2917, , _
                "Word created an empty temporary DOCX for row " & rowNumber
        End If
        If FileExists(finalDocxPath) Then
            Err.Raise vbObjectError + 2918, , _
                "Final output appeared before the temporary file was moved: " & _
                finalDocxPath
        End If
        Name currentTempPath As finalDocxPath
        currentTempPath = vbNullString
        generatedCount = generatedCount + 1
    Next rowNumber

    wdApp.ScreenUpdating = True
    wdApp.Quit WD_DO_NOT_SAVE_CHANGES
    Set wdApp = Nothing
    MsgBox generatedCount & " verified DOCX files created in:" & vbCrLf & _
           outputFolderPath, vbInformation, "Placeholder replacement complete"
    Exit Sub

CleanFail:
    errorNumber = Err.Number
    errorMessage = Err.Description
    On Error Resume Next
    If Not outputDoc Is Nothing Then _
        outputDoc.Close WD_DO_NOT_SAVE_CHANGES
    If Not templateDoc Is Nothing Then _
        templateDoc.Close WD_DO_NOT_SAVE_CHANGES
    If Len(currentTempPath) > 0 Then
        If FileExists(currentTempPath) Then Kill currentTempPath
    End If
    If Not wdApp Is Nothing Then
        wdApp.ScreenUpdating = True
        wdApp.Quit WD_DO_NOT_SAVE_CHANGES
    End If
    On Error GoTo 0
    If currentRow >= FIRST_DATA_ROW Then
        errorLocation = " at Excel row " & currentRow
    Else
        errorLocation = " during setup or template validation"
    End If
    MsgBox "Generation stopped" & errorLocation & "." & _
           vbCrLf & "Error " & errorNumber & ": " & errorMessage & _
           vbCrLf & "Previously completed final files were not removed.", _
           vbCritical, "Placeholder replacement stopped"
End Sub

Private Sub ValidateHeaders(ByVal ws As Worksheet, _
                            ByVal lastColumn As Long, _
                            ByVal headerColumns As Object, _
                            ByVal mappedTokens As Object)
    Dim columnNumber As Long
    Dim rawHeaderText As String
    Dim headerText As String
    Dim tokenText As String

    For columnNumber = 1 To lastColumn
        If IsError(ws.Cells(1, columnNumber).Value2) Then
            Err.Raise vbObjectError + 2920, , _
                "Header contains an Excel error in column " & columnNumber
        End If
        rawHeaderText = CStr(ws.Cells(1, columnNumber).Value2)
        headerText = Trim$(rawHeaderText)
        If Len(headerText) = 0 Then
            Err.Raise vbObjectError + 2921, , _
                "Header is blank in column " & columnNumber
        End If
        If StrComp(rawHeaderText, headerText, vbBinaryCompare) <> 0 Then
            Err.Raise vbObjectError + 2926, , _
                "Header has leading or trailing whitespace in column " & columnNumber
        End If
        If headerColumns.Exists(headerText) Then
            Err.Raise vbObjectError + 2922, , _
                "Duplicate header in columns " & headerColumns(headerText) & _
                " and " & columnNumber & ": " & headerText
        End If
        headerColumns.Add headerText, columnNumber

        If columnNumber >= 3 Then
            ValidateFieldHeader headerText, columnNumber
            tokenText = TOKEN_OPEN & headerText & TOKEN_CLOSE
            If mappedTokens.Exists(tokenText) Then
                Err.Raise vbObjectError + 2923, , _
                    "Duplicate mapped token: " & tokenText
            End If
            mappedTokens.Add tokenText, columnNumber
        End If
    Next columnNumber

    If Not headerColumns.Exists(HEADER_DOCUMENT_ID) Then
        Err.Raise vbObjectError + 2924, , _
            "Required header is missing: " & HEADER_DOCUMENT_ID
    End If
    If Not headerColumns.Exists(HEADER_OUTPUT_NAME) Then
        Err.Raise vbObjectError + 2925, , _
            "Required header is missing: " & HEADER_OUTPUT_NAME
    End If
End Sub

Private Sub ValidateFieldHeader(ByVal headerText As String, _
                                ByVal columnNumber As Long)
    Dim characterNumber As Long
    Dim characterText As String

    If Len(headerText) > 60 Then
        Err.Raise vbObjectError + 2930, , _
            "Mapped header is longer than 60 characters in column " & _
            columnNumber
    End If
    For characterNumber = 1 To Len(headerText)
        characterText = Mid$(headerText, characterNumber, 1)
        If Not (characterText Like "[A-Za-z0-9_]") Then
            Err.Raise vbObjectError + 2931, , _
                "Mapped headers may use only A-Z, a-z, 0-9, and underscore. " & _
                "Column " & columnNumber & ": " & headerText
        End If
    Next characterNumber
End Sub

Private Sub ValidateTemplateContract(ByVal doc As Object, _
                                     ByVal mappedTokens As Object)
    Dim templateTokens As Object
    Dim tokenItem As Variant

    Set templateTokens = CreateObject("Scripting.Dictionary")
    templateTokens.CompareMode = vbBinaryCompare
    CollectTokensFromDocument doc, templateTokens

    For Each tokenItem In mappedTokens.Keys
        If Not templateTokens.Exists(CStr(tokenItem)) Then
            Err.Raise vbObjectError + 2940, , _
                "Excel maps a token that is absent from the Word template: " & _
                CStr(tokenItem)
        End If
    Next tokenItem
    For Each tokenItem In templateTokens.Keys
        If Not mappedTokens.Exists(CStr(tokenItem)) Then
            Err.Raise vbObjectError + 2941, , _
                "Word contains a token with no matching Excel header: " & _
                CStr(tokenItem)
        End If
    Next tokenItem
End Sub

Private Sub CollectTokensFromDocument(ByVal doc As Object, _
                                      ByVal tokenDictionary As Object)
    Dim firstStory As Object
    Dim currentStory As Object

    For Each firstStory In doc.StoryRanges
        Set currentStory = firstStory
        Do
            CollectTokensFromText CStr(currentStory.Text), tokenDictionary
            Set currentStory = currentStory.NextStoryRange
        Loop Until currentStory Is Nothing
    Next firstStory
End Sub

Private Sub CollectTokensFromText(ByVal sourceText As String, _
                                  ByVal tokenDictionary As Object)
    Dim searchPosition As Long
    Dim openPosition As Long
    Dim closePosition As Long
    Dim tokenText As String
    Dim innerText As String

    searchPosition = 1
    Do
        openPosition = InStr(searchPosition, sourceText, TOKEN_OPEN, _
            vbBinaryCompare)
        If openPosition = 0 Then Exit Do
        closePosition = InStr(openPosition + Len(TOKEN_OPEN), sourceText, _
            TOKEN_CLOSE, vbBinaryCompare)
        If closePosition = 0 Then
            Err.Raise vbObjectError + 2942, , _
                "Word contains an opening {{ without a closing }}."
        End If
        tokenText = Mid$(sourceText, openPosition, _
            closePosition - openPosition + Len(TOKEN_CLOSE))
        innerText = Mid$(tokenText, Len(TOKEN_OPEN) + 1, _
            Len(tokenText) - Len(TOKEN_OPEN) - Len(TOKEN_CLOSE))
        If Len(innerText) = 0 Or InStr(innerText, TOKEN_OPEN) > 0 Then
            Err.Raise vbObjectError + 2943, , _
                "Word contains a malformed placeholder near: " & tokenText
        End If
        If tokenDictionary.Exists(tokenText) Then
            tokenDictionary(tokenText) = CLng(tokenDictionary(tokenText)) + 1
        Else
            tokenDictionary.Add tokenText, 1
        End If
        searchPosition = closePosition + Len(TOKEN_CLOSE)
    Loop
End Sub

Private Function ReplaceTokenInAllStories(ByVal doc As Object, _
                                           ByVal tokenText As String, _
                                           ByVal replacementText As String) As Long
    Dim firstStory As Object
    Dim currentStory As Object
    Dim searchRange As Object
    Dim styleValue As Variant

    For Each firstStory In doc.StoryRanges
        Set currentStory = firstStory
        Do
            Set searchRange = currentStory.Duplicate
            Do
                With searchRange.Find
                    .ClearFormatting
                    .Replacement.ClearFormatting
                    .Text = tokenText
                    .Forward = True
                    .Wrap = WD_FIND_STOP
                    .Format = False
                    .MatchCase = True
                    .MatchWholeWord = False
                    .MatchWildcards = False
                End With
                If Not searchRange.Find.Execute Then Exit Do
                If searchRange.Fields.Count > 0 Or _
                   searchRange.InlineShapes.Count > 0 Then
                    Err.Raise vbObjectError + 2950, , _
                        "Token overlaps a Word field or inline object: " & tokenText
                End If
                styleValue = searchRange.Style
                searchRange.Text = replacementText
                searchRange.Style = styleValue
                ReplaceTokenInAllStories = ReplaceTokenInAllStories + 1
                searchRange.Collapse WD_COLLAPSE_END
                searchRange.End = currentStory.End
            Loop
            Set currentStory = currentStory.NextStoryRange
        Loop Until currentStory Is Nothing
    Next firstStory
End Function

Private Function FirstTemplateToken(ByVal doc As Object) As String
    Dim firstStory As Object
    Dim currentStory As Object
    Dim sourceText As String
    Dim openPosition As Long
    Dim closePosition As Long

    For Each firstStory In doc.StoryRanges
        Set currentStory = firstStory
        Do
            sourceText = CStr(currentStory.Text)
            openPosition = InStr(1, sourceText, TOKEN_OPEN, vbBinaryCompare)
            If openPosition > 0 Then
                closePosition = InStr(openPosition + Len(TOKEN_OPEN), _
                    sourceText, TOKEN_CLOSE, vbBinaryCompare)
                If closePosition = 0 Then
                    FirstTemplateToken = Mid$(sourceText, openPosition, 80)
                Else
                    FirstTemplateToken = Mid$(sourceText, openPosition, _
                        closePosition - openPosition + Len(TOKEN_CLOSE))
                End If
                Exit Function
            End If
            Set currentStory = currentStory.NextStoryRange
        Loop Until currentStory Is Nothing
    Next firstStory
End Function

Private Function ReadValueText(ByVal sourceValue As Variant, _
                               ByVal fieldName As String, _
                               ByVal rowNumber As Long) As String
    If IsError(sourceValue) Then
        Err.Raise vbObjectError + 2960, , _
            "Excel error in row " & rowNumber & ", field " & fieldName
    End If
    If Not IsEmpty(sourceValue) And VarType(sourceValue) <> vbString Then
        Err.Raise vbObjectError + 2964, , _
            "Store document-ready text in row " & rowNumber & _
            ", field " & fieldName
    End If
    ReadValueText = CStr(sourceValue)
End Function

Private Sub ValidateReplacementText(ByVal replacementText As String, _
                                    ByVal fieldName As String, _
                                    ByVal rowNumber As Long)
    If Len(replacementText) > 3000 Then
        Err.Raise vbObjectError + 2961, , _
            "Text exceeds 3000 characters in row " & rowNumber & _
            ", field " & fieldName
    End If
    If InStr(replacementText, vbCr) > 0 Or _
       InStr(replacementText, vbLf) > 0 Or _
       InStr(replacementText, vbTab) > 0 Or _
       InStr(replacementText, Chr$(11)) > 0 Then
        Err.Raise vbObjectError + 2962, , _
            "This helper accepts single-line text only. Row " & _
            rowNumber & ", field " & fieldName
    End If
    If InStr(replacementText, TOKEN_OPEN) > 0 Or _
       InStr(replacementText, TOKEN_CLOSE) > 0 Then
        Err.Raise vbObjectError + 2963, , _
            "Replacement text contains placeholder braces in row " & _
            rowNumber & ", field " & fieldName
    End If
End Sub

Private Sub ValidateFileStem(ByVal fileStem As String, _
                             ByVal rowNumber As Long)
    Dim invalidCharacters As Variant
    Dim item As Variant
    Dim baseName As String
    Dim upperBaseName As String
    Dim characterNumber As Long
    Dim dotPosition As Long

    If Len(fileStem) > 120 Then
        Err.Raise vbObjectError + 2970, , _
            "OutputName exceeds 120 characters in row " & rowNumber
    End If
    If LCase$(Right$(fileStem, 5)) = ".docx" Then
        Err.Raise vbObjectError + 2974, , _
            "OutputName must not include .docx in row " & rowNumber
    End If
    For characterNumber = 1 To Len(fileStem)
        If AscW(Mid$(fileStem, characterNumber, 1)) < 32 Then
            Err.Raise vbObjectError + 2975, , _
                "OutputName contains a control character in row " & rowNumber
        End If
    Next characterNumber
    invalidCharacters = Array("\", "/", ":", "*", "?", Chr$(34), "<", ">", "|")
    For Each item In invalidCharacters
        If InStr(fileStem, CStr(item)) > 0 Then
            Err.Raise vbObjectError + 2971, , _
                "OutputName contains an invalid character in row " & rowNumber
        End If
    Next item
    If Right$(fileStem, 1) = "." Or Right$(fileStem, 1) = " " Then
        Err.Raise vbObjectError + 2972, , _
            "OutputName cannot end with a dot or space in row " & rowNumber
    End If
    baseName = fileStem
    dotPosition = InStr(1, baseName, ".", vbBinaryCompare)
    If dotPosition > 0 Then _
        baseName = Left$(baseName, dotPosition - 1)
    upperBaseName = UCase$(baseName)
    If IsReservedWindowsName(upperBaseName) Then
        Err.Raise vbObjectError + 2973, , _
            "OutputName is reserved by Windows in row " & rowNumber & _
            ": " & fileStem
    End If
End Sub

Private Function IsReservedWindowsName(ByVal upperBaseName As String) As Boolean
    Dim deviceNumber As Long
    Select Case upperBaseName
        Case "CON", "PRN", "AUX", "NUL"
            IsReservedWindowsName = True
            Exit Function
    End Select
    For deviceNumber = 1 To 9
        If upperBaseName = "COM" & CStr(deviceNumber) Or _
           upperBaseName = "LPT" & CStr(deviceNumber) Then
            IsReservedWindowsName = True
            Exit Function
        End If
    Next deviceNumber
    If upperBaseName = "COM" & ChrW$(&HB9) Or _
       upperBaseName = "COM" & ChrW$(&HB2) Or _
       upperBaseName = "COM" & ChrW$(&HB3) Or _
       upperBaseName = "LPT" & ChrW$(&HB9) Or _
       upperBaseName = "LPT" & ChrW$(&HB2) Or _
       upperBaseName = "LPT" & ChrW$(&HB3) Then
        IsReservedWindowsName = True
    End If
End Function

Private Function RowIsBlank(ByVal ws As Worksheet, _
                            ByVal rowNumber As Long, _
                            ByVal lastColumn As Long) As Boolean
    RowIsBlank = (Application.CountA( _
        ws.Range(ws.Cells(rowNumber, 1), _
                 ws.Cells(rowNumber, lastColumn))) = 0)
End Function

Private Function RequireWorksheet(ByVal wb As Workbook, _
                                  ByVal worksheetName As String) As Worksheet
    On Error Resume Next
    Set RequireWorksheet = wb.Worksheets(worksheetName)
    On Error GoTo 0
    If RequireWorksheet Is Nothing Then
        Err.Raise vbObjectError + 2980, , _
            "Required worksheet is missing: " & worksheetName
    End If
End Function

Private Function FileExists(ByVal filePath As String) As Boolean
    On Error Resume Next
    FileExists = (Len(Dir$(filePath, FILE_ATTRIBUTES)) > 0)
    On Error GoTo 0
End Function

Private Function FolderExists(ByVal folderPath As String) As Boolean
    Dim attributes As Long
    On Error Resume Next
    attributes = GetAttr(folderPath)
    FolderExists = (Err.Number = 0) And _
                   ((attributes And vbDirectory) = vbDirectory)
    Err.Clear
    On Error GoTo 0
End Function

Use the error message to fix the correct layer

Mapped token absent from Word

Excel has a header that the template does not use. Correct the header, add the exact tag, or remove the unused mapped column.

Word token has no header

The template contains an unknown or obsolete tag. Add the exact Excel field only if the document genuinely requires it.

Unreplaced token remains

A replacement introduced braces, the template changed after preflight, or a protected structure prevented the expected edit.

Field or inline object overlap

The tag is not plain static text. Move it outside that object or use a workflow designed for Word fields or images.

Unsafe replacement text

Prepare a clean single-line display column or use a separately tested multiline insertion routine.

Existing output

Review the earlier file and choose an approved new name. The helper never treats overwrite as a repair.

Run a six-record failure pilot

1. Normal record

Confirm all tags replace in the body and the DOCX reopens with the expected values.

2. Header tag

Place one mapped token in the primary header and confirm it is processed.

3. Text-box tag

Use a linked text-frame story and confirm the tag inventory and replacement both reach it.

4. Unknown Word tag

Add {{UnknownField}} and confirm preflight stops before any final file is created.

5. Missing mapped tag

Add an Excel header without its Word token and confirm the contract comparison reports it.

6. Existing filename

Create the intended output first and confirm the macro refuses to overwrite it.

Review beyond the tag gate

A clean token scan does not prove correct pagination, formatting, source accuracy, or release approval. Inspect representative DOCX files before scaling.

Use Factory for the standardized row-to-document workflow

DocxForge Pro Factory fits many independent Excel rows, one standard Word template, and one separate document per row.

Correct module

Use Factory after the header, tag, filename, and template contracts are stable.

Review Excel data

Confirm document-ready values, output names, selected rows, and the exact field set.

Review the template

Confirm the standard Word template and its literal text and image destinations before generation.

Where it does not fit

Contractor is for one case that creates several different documents from different Word templates.

DocxForge Pro Factory Excel data prepared for verified placeholder replacement
Review the row data, output names, and document-ready values.
DocxForge Pro Factory document settings for a standard Word template
Confirm the standard template and output settings.
Move from fragile replacement scripts to a controlled Factory workflowTry DocxForge Pro for 7 days free. Then $38 every 3 months • 14-day refund after purchase.
Factory workflowLiteral template tagsLocal processingDOCX + PDF
Start Free 7-Day Trial

Frequently asked questions

Why does a Word placeholder remain unchanged even when the Excel header looks correct?

The visible text may differ by case, braces, spaces, hidden characters, or location. The template can also contain a tag in a header, footer, or text box while a macro searches only the main document body. Compare the literal token and header, then search every relevant Word story.

Should placeholders use one brace or two braces?

Either convention can work, but one project must use one literal contract. This guide and VBA helper require {{FieldName}} and map it to the exact Excel header FieldName.

Does the VBA helper replace tags in headers and footers?

Yes. It walks the document StoryRanges and follows NextStoryRange so it can process the main story, available headers and footers, and linked text-frame stories. It still targets static text tokens, not Word field codes or inline objects.

Can the Excel cells contain dates, currency, or formulas?

The mapped cells must return document-ready text because the helper reads Value2. Prepare display strings in Excel first when dates, currency, percentages, leading zeros, or locale-specific formats must be preserved.

Does a successful replacement prove the document is ready to release?

No. The helper proves the mapped literal tokens were found and that no {{...}} token remains. Review the finished DOCX for formatting, pagination, business accuracy, permissions, and approval requirements.

Which DocxForge Pro module fits this workflow?

Factory fits many independent Excel rows, one standard Word template, and one separate output per row. Contractor fits one case that creates several different documents from different Word templates.

Standardize the tags once, then generate repeatable Word and PDF outputRun DocxForge Pro locally. 7 days free, then $38 every 3 months • 14-day refund after purchase.
Exact tag mappingOne Word templateRow-based outputLocal workflow
Start Free 7-Day Trial