How to Create Reusable Word Templates for Document Automation
Design a Word template as a controlled interface, not a decorated sample file. Define the data contract, tag locations, styles, tables, images, version rules, and release checks before the template reaches production.
Quick answer: separate the template contract from each document record
The template owns structure
Word owns page geometry, sections, headers, footers, styles, tables, fixed labels, and the exact destinations where dynamic content belongs.
The data source owns values
Excel owns record IDs, document-ready text, filenames, image references, processing status, and the fields required by the approved template version.
Do not promote a template because one sample looks correct. Audit the declared contract and run short, long, blank, image, table, and page-break records first.
Define the six parts of a reusable template
Purpose
Name the exact document type, owner, source table, review step, and final outputs. Avoid one template that tries to serve unrelated documents.
Data contract
List each required field, optional field, display format, maximum tested length, and whether blank values are allowed.
Layout contract
Fix page size, margins, section breaks, headers, footers, table widths, and image destinations.
Style system
Use named paragraph and character styles for headings, body text, labels, captions, and table content.
Generation contract
Document whether the workflow uses literal tags, content controls, bookmarks, fields, or another mechanism. Do not mix them silently.
Release contract
Record the approved version, pilot evidence, change owner, rollback copy, and the date production adopted it.
Write the tag contract before placing tags in Word
One literal syntax
For example, use {{ClientName}} consistently. Do not combine one-brace, double-brace, merge-field, and content-control conventions by accident.
Stable field names
Use letters, digits, and underscore. Treat case and spelling as part of the interface.
Expected location
Record whether each token belongs in BODY, HEADER, FOOTER, TEXTBOX, or may appear in ANY story.
Expected count
A repeated client name may appear three times. A unique document ID may appear once. Count changes should require review.
Unknown-token rule
Every literal token in Word needs a contract row. Old tags do not become harmless merely because the current generator ignores them.
Optional-value rule
Optional data does not mean an optional contract. Define what Word should show when the source value is blank.
Use columns A–C with exact headers Token, ExpectedLocation, and ExpectedCount. Example: {{ClientName}} | BODY | 2.
Build layout from styles and stable containers
Use named styles
Change a style definition once instead of repairing direct formatting across many paragraphs.
Keep tags uniformly formatted
Apply one style to the complete token. Mixed formatting inside a token makes replacement behavior harder to predict.
Control paragraph behavior
Test Keep with next, Keep lines together, widow/orphan control, page breaks, and spacing before and after.
Use fixed table logic
Choose widths, wrapping, row splitting, header-row repetition, and AutoFit behavior intentionally.
Separate fixed and dynamic text
Keep punctuation and labels outside a tag unless they truly belong to the source value.
Test every section
Different first page, odd/even pages, and later sections can contain separate headers and footers.
Official references: Word Document.Styles, StoryRanges, Document.ContentControls, and Revisions.
Define image and table behavior before real data arrives
Image source
Specify folder, filename, supported types, missing-image behavior, permissions, and whether the result must embed the binary.
Fit versus fill
Decide whether an image must fit completely inside a box or fill it with cropping. These are different results.
Anchor and wrapping
Prefer predictable inline placement unless a tested floating layout is genuinely required.
Long table values
Test long names, addresses, notes, URLs, and numbers so columns do not collapse or overflow.
Blank table values
Define whether blank content leaves an empty cell, removes a row, or triggers a review. Do not assume automatic conditional deletion.
DOCX and PDF check
Compare page breaks, image placement, table splitting, and header/footer output in both formats.
Release a template instead of overwriting the master
1. Work in a copy
Keep the current approved release immutable while the next version is edited and reviewed.
2. Resolve revisions
Turn off Track Changes and accept or reject pending revisions deliberately before release.
3. Review comments
Remove release-blocking comments. Retain only documented notes that belong in the distributed template.
4. Audit the contract
Compare every literal tag, location, and occurrence count against the approved TemplateContract sheet.
5. Run the pilot
Generate representative records and inspect Word and PDF output on the production desktop environment.
6. Promote and record
Publish the new master, note the adoption date, and preserve the earlier release for controlled rollback.
Free VBA helper: audit a reusable Word template
Save a writable Excel audit workbook as .xlsm. Put the Word master at Templates\ReusableTemplate.docx and define its literal tags on the TemplateContract sheet. The macro opens Word read-only and writes a timestamped audit sheet.
Token contract
Checks exact syntax, required location, expected count, missing tokens, and unknown template tokens.
All Word stories
Audits the main body, headers, footers, text boxes, and other available stories through StoryRanges.
Release signals
Reports Track Changes, pending revisions, comments, content controls, fields, protection, sections, and styles.
Read-only scope
Does not fix, accept, delete, replace, save, or generate any Word content. Review every ERROR and WARNING manually.
Option Explicit
Private Const CONTRACT_SHEET As String = "TemplateContract"
Private Const AUDIT_PREFIX As String = "TemplateAudit_"
Private Const TEMPLATE_FOLDER As String = "\Templates"
Private Const TEMPLATE_FILE As String = "ReusableTemplate.docx"
Private Const FIRST_CONTRACT_ROW As Long = 2
Private Const HEADER_TOKEN As String = "Token"
Private Const HEADER_LOCATION As String = "ExpectedLocation"
Private Const HEADER_COUNT As String = "ExpectedCount"
Private Const LOCATION_BODY As String = "BODY"
Private Const LOCATION_HEADER As String = "HEADER"
Private Const LOCATION_FOOTER As String = "FOOTER"
Private Const LOCATION_TEXTBOX As String = "TEXTBOX"
Private Const LOCATION_ANY As String = "ANY"
Private Const LOCATION_OTHER As String = "OTHER"
Private Const TOKEN_OPEN As String = "{{"
Private Const TOKEN_CLOSE As String = "}}"
Private Const KEY_SEPARATOR As String = "||"
Private Const WD_MAIN_TEXT_STORY As Long = 1
Private Const WD_TEXT_FRAME_STORY As Long = 5
Private Const WD_EVEN_PAGES_HEADER_STORY As Long = 6
Private Const WD_PRIMARY_HEADER_STORY As Long = 7
Private Const WD_EVEN_PAGES_FOOTER_STORY As Long = 8
Private Const WD_PRIMARY_FOOTER_STORY As Long = 9
Private Const WD_FIRST_PAGE_HEADER_STORY As Long = 10
Private Const WD_FIRST_PAGE_FOOTER_STORY As Long = 11
Private Const WD_DO_NOT_SAVE_CHANGES As Long = 0
Private Const WD_ALERTS_NONE As Long = 0
Private Const WD_NO_PROTECTION As Long = -1
Private Const FILE_ATTRIBUTES As Long = 39
Public Sub AuditReusableWordTemplate()
Dim wb As Workbook
Dim contractWs As Worksheet
Dim auditWs As Worksheet
Dim lastCell As Range
Dim lastRow As Long
Dim rowNumber As Long
Dim auditRow As Long
Dim tokenText As String
Dim rawLocation As String
Dim expectedLocation As String
Dim expectedCountValue As Variant
Dim expectedCount As Long
Dim actualCount As Long
Dim actualTotalCount As Long
Dim unexpectedCount As Long
Dim auditName As String
Dim templatePath As String
Dim detailText As String
Dim resultText As String
Dim contractTokens As Object
Dim expectedLocations As Object
Dim expectedCounts As Object
Dim contractRows As Object
Dim actualTokenCounts As Object
Dim actualLocationCounts As Object
Dim tokenItem As Variant
Dim wdApp As Object
Dim templateDoc As Object
Dim errorCount As Long
Dim warningCount As Long
Dim errorNumber As Long
Dim errorMessage As String
On Error GoTo CleanFail
Set wb = ThisWorkbook
If Len(wb.Path) = 0 Then
Err.Raise vbObjectError + 3000, , _
"Save this audit workbook as .xlsm before running the macro."
End If
If wb.ReadOnly Then
Err.Raise vbObjectError + 3001, , _
"Open a writable audit workbook before running the macro."
End If
If wb.ProtectStructure Then
Err.Raise vbObjectError + 3002, , _
"Unprotect the workbook structure before adding an audit sheet."
End If
Set contractWs = RequireWorksheet(wb, CONTRACT_SHEET)
ValidateContractHeaders contractWs
Set lastCell = contractWs.Range("A:C").Find(What:="*", _
After:=contractWs.Cells(1, 1), LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, MatchCase:=False)
If lastCell Is Nothing Then
Err.Raise vbObjectError + 3003, , _
"The TemplateContract sheet is empty."
End If
If lastCell.Row < FIRST_CONTRACT_ROW Then
Err.Raise vbObjectError + 3003, , _
"The TemplateContract sheet has no token rows."
End If
lastRow = lastCell.Row
Set contractTokens = CreateObject("Scripting.Dictionary")
contractTokens.CompareMode = vbBinaryCompare
Set expectedLocations = CreateObject("Scripting.Dictionary")
expectedLocations.CompareMode = vbBinaryCompare
Set expectedCounts = CreateObject("Scripting.Dictionary")
expectedCounts.CompareMode = vbBinaryCompare
Set contractRows = CreateObject("Scripting.Dictionary")
contractRows.CompareMode = vbBinaryCompare
For rowNumber = FIRST_CONTRACT_ROW To lastRow
If Application.CountA(contractWs.Range( _
contractWs.Cells(rowNumber, 1), _
contractWs.Cells(rowNumber, 3))) = 0 Then
Err.Raise vbObjectError + 3004, , _
"Blank row inside TemplateContract: row " & rowNumber
End If
tokenText = ReadContractText(contractWs.Cells(rowNumber, 1), _
HEADER_TOKEN, rowNumber)
rawLocation = ReadContractText(contractWs.Cells(rowNumber, 2), _
HEADER_LOCATION, rowNumber)
expectedLocation = UCase$(Trim$(rawLocation))
If StrComp(rawLocation, expectedLocation, vbBinaryCompare) <> 0 Then
Err.Raise vbObjectError + 3005, , _
"ExpectedLocation must be uppercase without outer spaces in row " & _
rowNumber
End If
ValidateTokenSyntax tokenText, "contract row " & rowNumber
ValidateExpectedLocation expectedLocation, rowNumber
expectedCountValue = contractWs.Cells(rowNumber, 3).Value2
If IsError(expectedCountValue) Then
Err.Raise vbObjectError + 3006, , _
"ExpectedCount must be an integer in row " & rowNumber
End If
If Not IsNumeric(expectedCountValue) Then
Err.Raise vbObjectError + 3006, , _
"ExpectedCount must be an integer in row " & rowNumber
End If
If CDbl(expectedCountValue) <> Fix(CDbl(expectedCountValue)) Then
Err.Raise vbObjectError + 3006, , _
"ExpectedCount must be an integer in row " & rowNumber
End If
expectedCount = CLng(expectedCountValue)
If expectedCount < 1 Or expectedCount > 100 Then
Err.Raise vbObjectError + 3007, , _
"ExpectedCount must be between 1 and 100 in row " & rowNumber
End If
If contractTokens.Exists(tokenText) Then
Err.Raise vbObjectError + 3008, , _
"Duplicate token in contract rows " & _
contractRows(tokenText) & " and " & rowNumber & ": " & tokenText
End If
contractTokens.Add tokenText, True
expectedLocations.Add tokenText, expectedLocation
expectedCounts.Add tokenText, expectedCount
contractRows.Add tokenText, rowNumber
Next rowNumber
templatePath = wb.Path & TEMPLATE_FOLDER & "\" & TEMPLATE_FILE
If Not FileExists(templatePath) Then
Err.Raise vbObjectError + 3009, , _
"Word template is missing: " & templatePath
End If
auditName = UniqueAuditSheetName(wb)
Set auditWs = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
auditWs.Name = auditName
WriteAuditHeaders auditWs
auditRow = 2
Application.ScreenUpdating = False
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)
Set actualTokenCounts = CreateObject("Scripting.Dictionary")
actualTokenCounts.CompareMode = vbBinaryCompare
Set actualLocationCounts = CreateObject("Scripting.Dictionary")
actualLocationCounts.CompareMode = vbBinaryCompare
CollectTemplateTokens templateDoc, actualTokenCounts, actualLocationCounts
For Each tokenItem In contractTokens.Keys
tokenText = CStr(tokenItem)
expectedLocation = CStr(expectedLocations(tokenText))
expectedCount = CLng(expectedCounts(tokenText))
actualTotalCount = DictionaryCount(actualTokenCounts, tokenText)
If expectedLocation = LOCATION_ANY Then
actualCount = actualTotalCount
unexpectedCount = 0
Else
actualCount = DictionaryCount(actualLocationCounts, _
LocationKey(tokenText, expectedLocation))
unexpectedCount = actualTotalCount - actualCount
End If
If actualCount = expectedCount And unexpectedCount = 0 Then
resultText = "PASS"
detailText = "Token count and location match the contract."
Else
resultText = "ERROR"
detailText = "Expected " & expectedCount & " in " & _
expectedLocation & "; found " & actualCount
If unexpectedCount > 0 Then
detailText = detailText & ", plus " & unexpectedCount & _
" in other locations"
End If
detailText = detailText & "."
End If
WriteAuditRow auditWs, auditRow, "TOKEN", tokenText, _
expectedLocation, expectedCount, actualCount, _
resultText, detailText, errorCount, warningCount
Next tokenItem
For Each tokenItem In actualTokenCounts.Keys
tokenText = CStr(tokenItem)
If Not contractTokens.Exists(tokenText) Then
WriteAuditRow auditWs, auditRow, "UNKNOWN TOKEN", tokenText, _
"Not in contract", 0, CLng(actualTokenCounts(tokenText)), _
"ERROR", "Template token has no contract row.", _
errorCount, warningCount
End If
Next tokenItem
WriteStructuralChecks templateDoc, auditWs, auditRow, _
errorCount, warningCount
WriteTemplateSummary templateDoc, auditWs, templatePath, _
actualTokenCounts.Count
auditWs.Columns("A:H").AutoFit
auditWs.Rows(1).Font.Bold = True
templateDoc.Close WD_DO_NOT_SAVE_CHANGES
Set templateDoc = Nothing
wdApp.ScreenUpdating = True
wdApp.Quit WD_DO_NOT_SAVE_CHANGES
Set wdApp = Nothing
wb.Save
Application.ScreenUpdating = True
MsgBox "Template audit created: " & auditName & vbCrLf & _
"Errors: " & errorCount & vbCrLf & _
"Warnings: " & warningCount, _
IIf(errorCount = 0, vbInformation, vbExclamation), _
"Reusable template audit"
Exit Sub
CleanFail:
errorNumber = Err.Number
errorMessage = Err.Description
On Error Resume Next
If Not templateDoc Is Nothing Then _
templateDoc.Close WD_DO_NOT_SAVE_CHANGES
If Not wdApp Is Nothing Then
wdApp.ScreenUpdating = True
wdApp.Quit WD_DO_NOT_SAVE_CHANGES
End If
Application.ScreenUpdating = True
On Error GoTo 0
MsgBox "Template audit stopped." & vbCrLf & _
"Error " & errorNumber & ": " & errorMessage, _
vbCritical, "Audit not completed"
End Sub
Private Sub ValidateContractHeaders(ByVal ws As Worksheet)
RequireExactHeader ws.Cells(1, 1), HEADER_TOKEN, "A1"
RequireExactHeader ws.Cells(1, 2), HEADER_LOCATION, "B1"
RequireExactHeader ws.Cells(1, 3), HEADER_COUNT, "C1"
End Sub
Private Sub RequireExactHeader(ByVal sourceCell As Range, _
ByVal expectedHeader As String, _
ByVal cellAddress As String)
Dim sourceValue As Variant
sourceValue = sourceCell.Value2
If IsError(sourceValue) Then
Err.Raise vbObjectError + 3010, , _
"Header contains an Excel error in " & cellAddress
End If
If VarType(sourceValue) <> vbString Then
Err.Raise vbObjectError + 3011, , _
"Header must be text in " & cellAddress
End If
If StrComp(CStr(sourceValue), expectedHeader, vbBinaryCompare) <> 0 Then
Err.Raise vbObjectError + 3012, , _
"Cell " & cellAddress & " must contain: " & expectedHeader
End If
End Sub
Private Function ReadContractText(ByVal sourceCell As Range, _
ByVal fieldName As String, _
ByVal rowNumber As Long) As String
Dim sourceValue As Variant
sourceValue = sourceCell.Value2
If IsError(sourceValue) Then
Err.Raise vbObjectError + 3013, , _
"Excel error in " & fieldName & ", row " & rowNumber
End If
If VarType(sourceValue) <> vbString Then
Err.Raise vbObjectError + 3014, , _
fieldName & " must be text in row " & rowNumber
End If
If Len(CStr(sourceValue)) = 0 Then
Err.Raise vbObjectError + 3015, , _
fieldName & " is blank in row " & rowNumber
End If
ReadContractText = CStr(sourceValue)
End Function
Private Sub ValidateTokenSyntax(ByVal tokenText As String, _
ByVal sourceLabel As String)
Dim innerText As String
Dim characterNumber As Long
Dim characterText As String
If Left$(tokenText, Len(TOKEN_OPEN)) <> TOKEN_OPEN Or _
Right$(tokenText, Len(TOKEN_CLOSE)) <> TOKEN_CLOSE Then
Err.Raise vbObjectError + 3020, , _
"Token must use {{FieldName}} in " & sourceLabel & _
": " & tokenText
End If
innerText = Mid$(tokenText, Len(TOKEN_OPEN) + 1, _
Len(tokenText) - Len(TOKEN_OPEN) - Len(TOKEN_CLOSE))
If Len(innerText) = 0 Or Len(innerText) > 60 Then
Err.Raise vbObjectError + 3021, , _
"Token name must contain 1 to 60 characters in " & sourceLabel
End If
For characterNumber = 1 To Len(innerText)
characterText = Mid$(innerText, characterNumber, 1)
If Not (characterText Like "[A-Za-z0-9_]") Then
Err.Raise vbObjectError + 3022, , _
"Token names may use only A-Z, a-z, 0-9, and underscore in " & _
sourceLabel & ": " & tokenText
End If
Next characterNumber
End Sub
Private Sub ValidateExpectedLocation(ByVal expectedLocation As String, _
ByVal rowNumber As Long)
Select Case expectedLocation
Case LOCATION_BODY, LOCATION_HEADER, LOCATION_FOOTER, _
LOCATION_TEXTBOX, LOCATION_ANY
Case Else
Err.Raise vbObjectError + 3030, , _
"ExpectedLocation must be BODY, HEADER, FOOTER, TEXTBOX, " & _
"or ANY in row " & rowNumber
End Select
End Sub
Private Sub CollectTemplateTokens(ByVal doc As Object, _
ByVal totalCounts As Object, _
ByVal locationCounts As Object)
Dim firstStory As Object
Dim currentStory As Object
Dim locationText As String
For Each firstStory In doc.StoryRanges
Set currentStory = firstStory
Do
locationText = StoryLocation(CLng(currentStory.StoryType))
CollectTokensFromText CStr(currentStory.Text), locationText, _
totalCounts, locationCounts
Set currentStory = currentStory.NextStoryRange
Loop Until currentStory Is Nothing
Next firstStory
End Sub
Private Sub CollectTokensFromText(ByVal sourceText As String, _
ByVal locationText As String, _
ByVal totalCounts As Object, _
ByVal locationCounts As Object)
Dim searchPosition As Long
Dim openPosition As Long
Dim closePosition As Long
Dim tokenText As String
Dim locationKeyText 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 + 3040, , _
"Template contains an opening {{ without a closing }} in " & _
locationText
End If
tokenText = Mid$(sourceText, openPosition, _
closePosition - openPosition + Len(TOKEN_CLOSE))
ValidateTokenSyntax tokenText, "template " & locationText
IncrementDictionary totalCounts, tokenText
locationKeyText = LocationKey(tokenText, locationText)
IncrementDictionary locationCounts, locationKeyText
searchPosition = closePosition + Len(TOKEN_CLOSE)
Loop
End Sub
Private Function StoryLocation(ByVal storyType As Long) As String
Select Case storyType
Case WD_MAIN_TEXT_STORY
StoryLocation = LOCATION_BODY
Case WD_EVEN_PAGES_HEADER_STORY, WD_PRIMARY_HEADER_STORY, _
WD_FIRST_PAGE_HEADER_STORY
StoryLocation = LOCATION_HEADER
Case WD_EVEN_PAGES_FOOTER_STORY, WD_PRIMARY_FOOTER_STORY, _
WD_FIRST_PAGE_FOOTER_STORY
StoryLocation = LOCATION_FOOTER
Case WD_TEXT_FRAME_STORY
StoryLocation = LOCATION_TEXTBOX
Case Else
StoryLocation = LOCATION_OTHER
End Select
End Function
Private Function LocationKey(ByVal tokenText As String, _
ByVal locationText As String) As String
LocationKey = tokenText & KEY_SEPARATOR & locationText
End Function
Private Sub IncrementDictionary(ByVal dictionaryObject As Object, _
ByVal keyText As String)
If dictionaryObject.Exists(keyText) Then
dictionaryObject(keyText) = CLng(dictionaryObject(keyText)) + 1
Else
dictionaryObject.Add keyText, 1
End If
End Sub
Private Function DictionaryCount(ByVal dictionaryObject As Object, _
ByVal keyText As String) As Long
If dictionaryObject.Exists(keyText) Then _
DictionaryCount = CLng(dictionaryObject(keyText))
End Function
Private Sub WriteStructuralChecks(ByVal doc As Object, _
ByVal auditWs As Worksheet, _
ByRef auditRow As Long, _
ByRef errorCount As Long, _
ByRef warningCount As Long)
Dim revisionCount As Long
Dim fieldCount As Long
Dim contentControlCount As Long
Dim commentCount As Long
Dim protectionType As Long
revisionCount = CountRevisionsInAllStories(doc)
fieldCount = CountFieldsInAllStories(doc)
contentControlCount = CLng(doc.ContentControls.Count)
commentCount = CLng(doc.Comments.Count)
protectionType = CLng(doc.ProtectionType)
WriteAuditRow auditWs, auditRow, "STRUCTURE", "Track revisions", _
"Off", 0, IIf(CBool(doc.TrackRevisions), 1, 0), _
IIf(CBool(doc.TrackRevisions), "ERROR", "PASS"), _
IIf(CBool(doc.TrackRevisions), _
"Turn off Track Changes before releasing the template.", _
"Track Changes is off."), errorCount, warningCount
WriteAuditRow auditWs, auditRow, "STRUCTURE", "Pending revisions", _
"None", 0, revisionCount, _
IIf(revisionCount = 0, "PASS", "ERROR"), _
IIf(revisionCount = 0, "No tracked revisions found.", _
"Resolve tracked revisions before release."), _
errorCount, warningCount
WriteAuditRow auditWs, auditRow, "STRUCTURE", "Comments", _
"Reviewed", 0, commentCount, _
IIf(commentCount = 0, "PASS", "WARNING"), _
IIf(commentCount = 0, "No comments found.", _
"Review and remove release-blocking comments."), _
errorCount, warningCount
WriteAuditRow auditWs, auditRow, "STRUCTURE", "Content controls", _
"Documented", 0, contentControlCount, _
IIf(contentControlCount = 0, "PASS", "WARNING"), _
IIf(contentControlCount = 0, _
"No content controls found.", _
"This audit checks literal tags; document any separate content-control contract."), _
errorCount, warningCount
WriteAuditRow auditWs, auditRow, "STRUCTURE", "Word fields", _
"Informational", 0, fieldCount, "INFO", _
"Fields are counted but not validated by the literal-tag contract.", _
errorCount, warningCount
WriteAuditRow auditWs, auditRow, "STRUCTURE", "Protection", _
"Documented", WD_NO_PROTECTION, protectionType, "INFO", _
"ProtectionType is reported; test the production replacement method separately.", _
errorCount, warningCount
End Sub
Private Function CountRevisionsInAllStories(ByVal doc As Object) As Long
Dim firstStory As Object
Dim currentStory As Object
For Each firstStory In doc.StoryRanges
Set currentStory = firstStory
Do
CountRevisionsInAllStories = CountRevisionsInAllStories + _
CLng(currentStory.Revisions.Count)
Set currentStory = currentStory.NextStoryRange
Loop Until currentStory Is Nothing
Next firstStory
End Function
Private Function CountFieldsInAllStories(ByVal doc As Object) As Long
Dim firstStory As Object
Dim currentStory As Object
For Each firstStory In doc.StoryRanges
Set currentStory = firstStory
Do
CountFieldsInAllStories = CountFieldsInAllStories + _
CLng(currentStory.Fields.Count)
Set currentStory = currentStory.NextStoryRange
Loop Until currentStory Is Nothing
Next firstStory
End Function
Private Sub WriteTemplateSummary(ByVal doc As Object, _
ByVal auditWs As Worksheet, _
ByVal templatePath As String, _
ByVal distinctTokenCount As Long)
auditWs.Range("J1").Value2 = "Template path"
auditWs.Range("K1").Value2 = templatePath
auditWs.Range("J2").Value2 = "Template bytes"
auditWs.Range("K2").Value2 = FileLen(templatePath)
auditWs.Range("J3").Value2 = "Sections"
auditWs.Range("K3").Value2 = doc.Sections.Count
auditWs.Range("J4").Value2 = "Styles"
auditWs.Range("K4").Value2 = doc.Styles.Count
auditWs.Range("J5").Value2 = "Custom styles"
auditWs.Range("K5").Value2 = CountCustomStyles(doc)
auditWs.Range("J6").Value2 = "Distinct tokens"
auditWs.Range("K6").Value2 = distinctTokenCount
auditWs.Range("J7").Value2 = "Audit generated"
auditWs.Range("K7").Value = Now
End Sub
Private Function CountCustomStyles(ByVal doc As Object) As Long
Dim styleItem As Object
For Each styleItem In doc.Styles
If Not CBool(styleItem.BuiltIn) Then _
CountCustomStyles = CountCustomStyles + 1
Next styleItem
End Function
Private Sub WriteAuditHeaders(ByVal auditWs As Worksheet)
auditWs.Cells(1, 1).Value2 = "CheckType"
auditWs.Cells(1, 2).Value2 = "TokenOrItem"
auditWs.Cells(1, 3).Value2 = "ExpectedLocation"
auditWs.Cells(1, 4).Value2 = "ExpectedCount"
auditWs.Cells(1, 5).Value2 = "ActualCount"
auditWs.Cells(1, 6).Value2 = "Result"
auditWs.Cells(1, 7).Value2 = "Details"
auditWs.Cells(1, 8).Value2 = "CheckedAt"
End Sub
Private Sub WriteAuditRow(ByVal auditWs As Worksheet, _
ByRef auditRow As Long, _
ByVal checkType As String, _
ByVal tokenOrItem As String, _
ByVal expectedLocation As String, _
ByVal expectedCount As Long, _
ByVal actualCount As Long, _
ByVal resultText As String, _
ByVal detailsText As String, _
ByRef errorCount As Long, _
ByRef warningCount As Long)
auditWs.Cells(auditRow, 1).Value2 = checkType
auditWs.Cells(auditRow, 2).Value2 = tokenOrItem
auditWs.Cells(auditRow, 3).Value2 = expectedLocation
auditWs.Cells(auditRow, 4).Value2 = expectedCount
auditWs.Cells(auditRow, 5).Value2 = actualCount
auditWs.Cells(auditRow, 6).Value2 = resultText
auditWs.Cells(auditRow, 7).Value2 = detailsText
auditWs.Cells(auditRow, 8).Value = Now
If resultText = "ERROR" Then errorCount = errorCount + 1
If resultText = "WARNING" Then warningCount = warningCount + 1
auditRow = auditRow + 1
End Sub
Private Function UniqueAuditSheetName(ByVal wb As Workbook) As String
Dim baseName As String
Dim candidateName As String
Dim suffixNumber As Long
baseName = AUDIT_PREFIX & Format$(Now, "yymmdd_hhnnss")
candidateName = Left$(baseName, 31)
Do While WorksheetExists(wb, candidateName)
suffixNumber = suffixNumber + 1
candidateName = Left$(baseName, 27) & "_" & _
Format$(suffixNumber, "000")
Loop
UniqueAuditSheetName = candidateName
End Function
Private Function WorksheetExists(ByVal wb As Workbook, _
ByVal worksheetName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = wb.Worksheets(worksheetName)
WorksheetExists = Not ws Is Nothing
On Error GoTo 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 + 3050, , _
"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 FunctionInterpret the audit before changing the template
Missing contract token
The declared tag is absent, appears too few times, or is in the wrong story. Confirm intent before adding it.
Unknown Word token
The template contains a literal tag with no contract row. It may be obsolete, misspelled, or undocumented.
Unexpected location
A token expected in BODY also appears in a header, footer, text box, or another story.
Tracked changes
The master still contains editing state. Resolve it in the working copy rather than letting the audit accept changes automatically.
Comments or content controls
A warning asks for review. These objects may be intentional, but the literal-tag contract does not define their behavior.
Clean audit
PASS means the declared static contract matched this file. It does not prove generation, formatting, or final PDF correctness.
Run a six-record reusable-template pilot
1. Typical record
Verify normal content, page count, headings, tables, images, and filenames.
2. Maximum-length text
Use the longest approved names, addresses, notes, and identifiers.
3. Allowed blanks
Confirm every optional field produces the documented blank-state result.
4. Image extremes
Test portrait, landscape, small, and maximum-size approved images.
5. Multi-page tables
Confirm header rows, row splitting, page breaks, and repeated section elements.
6. Reopen and export
Reopen the DOCX and compare the PDF before approving the new master release.
Test with copies of the template, source data, images, and output folder. Do not use live records to discover structural defects.
Use Factory after approving the reusable template
DocxForge Pro Factory fits many independent Excel rows, one approved Word template, and one separate output per row.
Correct module
Factory fits a standardized row-to-document process built around one reusable template release.
Review source data
Confirm field names, document-ready values, image references, output names, and selected rows.
Review template settings
Confirm the approved master, literal tags, image destinations, and output requirements.
Where it does not fit
Contractor is for one case that creates several different documents from different Word templates.


Frequently asked questions
What makes a Word template reusable?
A reusable template has one documented purpose, a stable data contract, named styles, controlled tables and image areas, predictable page behavior, and a release process. Reuse means another approved record can be generated without rebuilding layout or guessing field names.
Should I use literal tags or Word content controls?
Choose one primary mechanism for each workflow and document it. Literal tags are easy to inspect and map. Content controls provide structured regions but require a separate title, tag, locking, and replacement contract. Mixing both without ownership increases ambiguity.
How should I version reusable templates?
Store an immutable approved release, record its version outside the filename when traceability requires it, and make changes in a working copy. Re-run the contract audit and pilot before promoting a new release.
Does the VBA audit modify the Word template?
No. It opens Templates\ReusableTemplate.docx read-only, inventories literal tags and structural conditions, closes Word without saving, and writes the audit results to the Excel audit workbook.
Does a clean template audit prove every generated document is correct?
No. The audit checks the declared template contract, tracked changes, comments, and selected structural signals. It does not validate source data, replacement behavior, pagination after long values, images, PDF rendering, or release approval.
Which DocxForge Pro module fits one reusable template and many rows?
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.