Legal and Advisory Intake

How to Automate Intake Forms for Legal and Advisory Teams

Turn one reviewed intake case into a controlled set of different Word and PDF documents, with explicit template contracts, local input snapshots, guarded filenames, and a release review.

One intake case
Different templates
Controlled bookmarks
DOCX + PDF
This is Contractor logic. Generation does not clear conflicts, verify identity, create an engagement, authorize advice, or approve release.

Quick answer: separate the intake case from its document register

Keep the reviewed client and matter data on one IntakeCase row. List every approved intake-stage document on DocumentRegister, with its own Word template, output suffix, exact bookmark contract, optional brand image, and status. Generate the pack only after the case and register pass preflight.

How this differs from the existing one-template article

Excel → Word → PDF Workflow for Legal Intake Documents covers many independent intake rows using one standard template. This guide covers one intake case that needs several different documents from different templates.

Create one IntakeCase row in exact A–I order

Required column order in row 1

A IntakeID; B ClientReference; C ClientName; D MatterType; E IntakeDateDisplay; F ContactDisplay; G AssignedProfessional; H IntakeSummary; I IntakeStatus.

Stable intake identity

Store IntakeID and ClientReference as exact text. Use IntakeID in filenames and keep it safe for Windows paths.

Client identity

Enter the reviewed client name intended for the pack. Identity verification and party-role confirmation remain separate controls.

Matter classification

Use MatterType as reviewed routing text. It does not decide eligibility, legal category, jurisdiction, or required documents automatically.

Document-ready date

Store IntakeDateDisplay as the exact wording intended for Word instead of relying on an Excel date format.

Contact and assignment

ContactDisplay is optional unless a template contract requires it. AssignedProfessional identifies the responsible internal reviewer or owner.

Multiline summary and status

Store a meaningful IntakeSummary with ordinary line breaks and use READY, HOLD, or DONE exactly. The free example runs only READY.

Create the DocumentRegister in exact A–F order

Required column order in row 1

A DocumentKey; B TemplateFile; C OutputSuffix; D RequiredBookmarks; E BrandImageFile; F DocumentStatus.

DocumentKey

Use a stable internal key such as INTAKE_ACK, CONFLICT_SUMMARY, INFO_REQUEST, or CONSULTATION_BRIEF.

TemplateFile

Reference one approved DOCX filename under Templates. Approved rows must not reuse the same template file in this example.

OutputSuffix

Use a safe suffix such as Intake_Acknowledgment. The macro validates the combined IntakeID_OutputSuffix name during preflight.

RequiredBookmarks

List exact, case-sensitive bookmark names separated by semicolons without padding. Every approved template must include IntakeID and ClientName.

BrandImageFile

Provide a filename under Assets\BrandImages only when RequiredBookmarks includes BrandImage; otherwise leave it blank.

DocumentStatus

Use APPROVED for documents included in the current pack and RETIRED for registry rows that must not generate output.

Give every Word template its own explicit contract

Allowed text bookmarks

Use IntakeID, ClientReference, ClientName, MatterType, IntakeDateDisplay, ContactDisplay, AssignedProfessional, and IntakeSummary.

Optional image bookmark

Use BrandImage only when the template needs an approved logo. Keep its range free of fields, content controls, existing images, and paragraph markers.

Required common identity

Every approved template must require IntakeID and ClientName so the generated pack can be reconciled to the reviewed case.

Exact contract matching

A listed bookmark must exist. An allowed bookmark present in the template but absent from RequiredBookmarks is treated as a contract error.

Clean review state

Turn off Track Changes, resolve revisions in every story, and remove comments before approving a template.

Different purpose, different template

Do not force an acknowledgment, conflict summary, request checklist, and consultation brief into one generic document when their purposes differ.

Keep intake automation inside the firm’s decision controls

Conflict checks

Do not treat a generated conflict summary as clearance. Complete the approved conflict-search and decision process separately.

Identity and authority

Verify the client, representatives, entities, beneficial owners, and authority using the firm’s approved process.

Engagement boundary

An intake acknowledgment or information request does not itself create an engagement, retainer, fiduciary duty, or advice relationship.

Sensitive data

Collect only necessary data, restrict workbook and output access, and apply approved retention, deletion, and incident-handling rules.

Template approval

Confirm that each actual DOCX is the released template for its purpose. A matching filename and bookmark list do not authenticate its wording.

Release ownership

Assign a person to review the complete document set, resolve exceptions, approve recipients, and record release or non-release.

Free Excel VBA example: generate one controlled intake pack

Save the workbook as .xlsm. Create IntakeCase and DocumentRegister, place approved DOCX files under Templates, optional logos under Assets\BrandImages, and run GenerateLegalAdvisoryIntakePack. The run keeps InputSnapshot, Staging, and Completed folders under GeneratedIntakePacks.

Excel VBA — guarded legal and advisory intake pack Contractor logic
Option Explicit

Private Const CASE_SHEET As String = "IntakeCase"
Private Const REGISTER_SHEET As String = "DocumentRegister"
Private Const STATUS_READY As String = "READY"
Private Const STATUS_HOLD As String = "HOLD"
Private Const STATUS_DONE As String = "DONE"
Private Const DOC_APPROVED As String = "APPROVED"
Private Const DOC_RETIRED As String = "RETIRED"
Private Const WD_FORMAT_DOCX As Long = 12
Private Const WD_EXPORT_PDF As Long = 17
Private Const WD_ALERTS_NONE As Long = 0
Private Const WD_DO_NOT_SAVE_CHANGES As Long = 0
Private Const WD_COLLAPSE_START As Long = 1
Private Const OFFICE_TRUE As Long = -1
Private Const POINTS_PER_CM As Double = 28.3464567

Public Sub GenerateLegalAdvisoryIntakePack()
    Dim wb As Workbook
    Dim caseWs As Worksheet
    Dim registerWs As Worksheet
    Dim fso As Object
    Dim wdApp As Object
    Dim doc As Object
    Dim caseData As Variant
    Dim registerData As Variant
    Dim templateSnapshots As Object
    Dim brandImageSnapshots As Object
    Dim documentKeys As Object
    Dim templateFiles As Object
    Dim outputSuffixes As Object
    Dim requiredBookmarks As Object
    Dim intakeId As String
    Dim clientReference As String
    Dim clientName As String
    Dim matterType As String
    Dim intakeDateDisplay As String
    Dim contactDisplay As String
    Dim assignedProfessional As String
    Dim intakeSummary As String
    Dim intakeStatus As String
    Dim documentKey As String
    Dim templateFile As String
    Dim outputSuffix As String
    Dim bookmarkContract As String
    Dim brandImageFile As String
    Dim documentStatus As String
    Dim templateFolder As String
    Dim brandImageFolder As String
    Dim outputRoot As String
    Dim runFolder As String
    Dim inputFolder As String
    Dim templateSnapshotFolder As String
    Dim brandImageSnapshotFolder As String
    Dim stagingFolder As String
    Dim completedFolder As String
    Dim sourcePath As String
    Dim snapshotPath As String
    Dim tempDocxPath As String
    Dim tempPdfPath As String
    Dim finalDocxPath As String
    Dim finalPdfPath As String
    Dim outputStem As String
    Dim lastRegisterRow As Long
    Dim dataRow As Long
    Dim excelRow As Long
    Dim approvedCount As Long
    Dim generatedCount As Long
    Dim previousScreenUpdating As Boolean
    Dim previousEnableEvents As Boolean
    Dim stateCaptured As Boolean
    Dim currentStep As String
    Dim errorNumber As Long
    Dim errorDescription As String
    Dim finalStatusPending As Boolean
    Dim statusRecoveryMessage As String

    On Error GoTo CleanFail
    Set wb = ThisWorkbook
    previousScreenUpdating = Application.ScreenUpdating
    previousEnableEvents = Application.EnableEvents
    stateCaptured = True
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    currentStep = "checking the macro-enabled workbook"
    RequireWritableMacroWorkbook wb
    Set caseWs = RequireWorksheet(wb, CASE_SHEET)
    Set registerWs = RequireWorksheet(wb, REGISTER_SHEET)
    If caseWs.ProtectContents Or registerWs.ProtectContents Then
        Err.Raise vbObjectError + 5100, , _
            "IntakeCase and DocumentRegister must allow status updates."
    End If
    ValidateCaseHeaders caseWs
    ValidateRegisterHeaders registerWs
    RequireOneCaseRow caseWs

    caseData = caseWs.Range("A2:I2").Value2
    intakeId = ReadRequiredText(caseData(1, 1), "IntakeID", 2)
    clientReference = ReadRequiredText(caseData(1, 2), "ClientReference", 2)
    clientName = ReadRequiredText(caseData(1, 3), "ClientName", 2)
    matterType = ReadRequiredText(caseData(1, 4), "MatterType", 2)
    intakeDateDisplay = ReadRequiredText( _
        caseData(1, 5), "IntakeDateDisplay", 2)
    contactDisplay = ReadOptionalText(caseData(1, 6), "ContactDisplay", 2)
    assignedProfessional = ReadRequiredText(caseData(1, 7), "AssignedProfessional", 2)
    intakeSummary = ReadRequiredMultilineText( _
        caseData(1, 8), "IntakeSummary", 2)
    intakeStatus = ReadRequiredText(caseData(1, 9), "IntakeStatus", 2)
    ValidateIntakeStatus intakeStatus
    If intakeStatus <> STATUS_READY Then
        Err.Raise vbObjectError + 5101, , _
            "IntakeCase row 2 must be exactly READY for generation."
    End If
    ValidateFileComponent intakeId, "IntakeID", 2

    templateFolder = JoinPath(wb.Path, "Templates")
    brandImageFolder = JoinPath(JoinPath(wb.Path, "Assets"), "BrandImages")
    outputRoot = JoinPath(wb.Path, "GeneratedIntakePacks")
    RequireFolder templateFolder, "template folder"

    lastRegisterRow = FindLastDataRow(registerWs, 6)
    If lastRegisterRow < 2 Then
        Err.Raise vbObjectError + 5102, , _
            "DocumentRegister has no document rows."
    End If
    registerData = registerWs.Range("A2:F" & lastRegisterRow).Value2
    Set documentKeys = NewTextDictionary(vbTextCompare)
    Set templateFiles = NewTextDictionary(vbTextCompare)
    Set outputSuffixes = NewTextDictionary(vbTextCompare)

    currentStep = "preflighting the document register"
    For dataRow = 1 To UBound(registerData, 1)
        excelRow = dataRow + 1
        If Not DataRowIsBlank(registerData, dataRow, 6) Then
            documentStatus = ReadRequiredText( _
                registerData(dataRow, 6), "DocumentStatus", excelRow)
            ValidateDocumentStatus documentStatus, excelRow
            If documentStatus = DOC_APPROVED Then
                documentKey = ReadRequiredText( _
                    registerData(dataRow, 1), "DocumentKey", excelRow)
                templateFile = ReadRequiredText( _
                    registerData(dataRow, 2), "TemplateFile", excelRow)
                outputSuffix = ReadRequiredText( _
                    registerData(dataRow, 3), "OutputSuffix", excelRow)
                bookmarkContract = ReadRequiredText( _
                    registerData(dataRow, 4), "RequiredBookmarks", excelRow)
                brandImageFile = ReadOptionalText( _
                    registerData(dataRow, 5), "BrandImageFile", excelRow)

                ValidateKey documentKey, "DocumentKey", excelRow
                ValidateDocxFileName templateFile, excelRow
                ValidateFileComponent outputSuffix, "OutputSuffix", excelRow
                ValidateFileComponent intakeId & "_" & outputSuffix, _
                    "combined output name", excelRow
                AddUnique documentKeys, documentKey, "DocumentKey", excelRow
                AddUnique templateFiles, templateFile, "TemplateFile", excelRow
                AddUnique outputSuffixes, outputSuffix, "OutputSuffix", excelRow
                Set requiredBookmarks = ParseBookmarkContract( _
                    bookmarkContract, excelRow)
                If requiredBookmarks.Exists("ContactDisplay") And _
                   Len(contactDisplay) = 0 Then
                    Err.Raise vbObjectError + 5159, , _
                        "ContactDisplay is required by the template contract " & _
                        "on DocumentRegister row " & excelRow & "."
                End If
                ValidateBrandImageContract requiredBookmarks, brandImageFile, excelRow

                sourcePath = JoinPath(templateFolder, templateFile)
                RequireNonemptyFile sourcePath, _
                    "template on DocumentRegister row " & excelRow
                If Len(brandImageFile) > 0 Then
                    ValidateImageFileName brandImageFile, excelRow
                    sourcePath = JoinPath(brandImageFolder, brandImageFile)
                    RequireNonemptyFile sourcePath, _
                        "brand image on DocumentRegister row " & excelRow
                End If
                approvedCount = approvedCount + 1
            End If
        End If
    Next dataRow
    If approvedCount = 0 Then
        Err.Raise vbObjectError + 5103, , _
            "DocumentRegister has no rows marked exactly APPROVED."
    End If

    currentStep = "saving the preflighted workbook"
    wb.Save
    Set fso = CreateObject("Scripting.FileSystemObject")
    EnsureFolder outputRoot
    runFolder = CreateRunFolder(fso, outputRoot, intakeId)
    inputFolder = JoinPath(runFolder, "InputSnapshot")
    templateSnapshotFolder = JoinPath(inputFolder, "Templates")
    brandImageSnapshotFolder = JoinPath(inputFolder, "BrandImages")
    stagingFolder = JoinPath(runFolder, "Staging")
    completedFolder = JoinPath(runFolder, "Completed")
    fso.CreateFolder inputFolder
    fso.CreateFolder templateSnapshotFolder
    fso.CreateFolder brandImageSnapshotFolder
    fso.CreateFolder stagingFolder
    fso.CreateFolder completedFolder
    Set templateSnapshots = NewTextDictionary(vbTextCompare)
    Set brandImageSnapshots = NewTextDictionary(vbTextCompare)

    currentStep = "creating the controlled input snapshot"
    For dataRow = 1 To UBound(registerData, 1)
        If CStr(registerData(dataRow, 6)) = DOC_APPROVED Then
            templateFile = CStr(registerData(dataRow, 2))
            sourcePath = JoinPath(templateFolder, templateFile)
            snapshotPath = JoinPath(templateSnapshotFolder, templateFile)
            CopyFileToSnapshot fso, sourcePath, snapshotPath, _
                "template " & templateFile
            templateSnapshots.Add templateFile, snapshotPath

            brandImageFile = CStr(registerData(dataRow, 5))
            If Len(brandImageFile) > 0 And _
               Not brandImageSnapshots.Exists(brandImageFile) Then
                sourcePath = JoinPath(brandImageFolder, brandImageFile)
                snapshotPath = JoinPath(brandImageSnapshotFolder, brandImageFile)
                CopyFileToSnapshot fso, sourcePath, snapshotPath, _
                    "brand image " & brandImageFile
                brandImageSnapshots.Add brandImageFile, snapshotPath
            End If
        End If
    Next dataRow

    currentStep = "starting Microsoft Word Desktop"
    Set wdApp = CreateObject("Word.Application")
    wdApp.Visible = False
    wdApp.DisplayAlerts = WD_ALERTS_NONE
    wdApp.ScreenUpdating = False

    For dataRow = 1 To UBound(registerData, 1)
        excelRow = dataRow + 1
        If CStr(registerData(dataRow, 6)) = DOC_APPROVED Then
            currentStep = "rechecking the intake case and register row " & excelRow
            RequireRangeUnchanged caseWs.Range("A2:I2"), caseData, 1, 9, _
                "IntakeCase row 2"
            RequireRangeUnchanged registerWs.Range("A" & excelRow & _
                ":F" & excelRow), registerData, dataRow, 6, _
                "DocumentRegister row " & excelRow

            documentKey = CStr(registerData(dataRow, 1))
            templateFile = CStr(registerData(dataRow, 2))
            outputSuffix = CStr(registerData(dataRow, 3))
            bookmarkContract = CStr(registerData(dataRow, 4))
            brandImageFile = CStr(registerData(dataRow, 5))
            Set requiredBookmarks = ParseBookmarkContract( _
                bookmarkContract, excelRow)
            outputStem = intakeId & "_" & outputSuffix
            ValidateFileComponent outputStem, "combined output name", excelRow
            tempDocxPath = JoinPath(stagingFolder, outputStem & ".docx")
            tempPdfPath = JoinPath(stagingFolder, outputStem & ".pdf")
            finalDocxPath = JoinPath(completedFolder, outputStem & ".docx")
            finalPdfPath = JoinPath(completedFolder, outputStem & ".pdf")
            RequireTargetAbsent tempDocxPath
            RequireTargetAbsent tempPdfPath
            RequireTargetAbsent finalDocxPath
            RequireTargetAbsent finalPdfPath

            currentStep = "generating " & documentKey
            Set doc = wdApp.Documents.Open( _
                templateSnapshots(templateFile), False, True, False)
            ValidateTemplate doc, requiredBookmarks, templateFile
            PopulateRequiredBookmarks doc, requiredBookmarks, _
                intakeId, clientReference, clientName, matterType, _
                intakeDateDisplay, contactDisplay, assignedProfessional, _
                intakeSummary, brandImageFile, brandImageSnapshots
            ValidateResultBeforeSave doc, requiredBookmarks, documentKey
            doc.SaveAs2 tempDocxPath, WD_FORMAT_DOCX
            doc.ExportAsFixedFormat tempPdfPath, WD_EXPORT_PDF, False, 0, _
                0, 1, 1, 0, False, True, 0, True, True, False
            doc.Close WD_DO_NOT_SAVE_CHANGES
            Set doc = Nothing

            RequireNonemptyFile tempDocxPath, "staged DOCX " & documentKey
            RequireNonemptyFile tempPdfPath, "staged PDF " & documentKey
            Name tempDocxPath As finalDocxPath
            Name tempPdfPath As finalPdfPath
            generatedCount = generatedCount + 1
        End If
    Next dataRow

    currentStep = "confirming the complete intake case and document register"
    If FindLastDataRow(caseWs, 9) <> 2 Then
        Err.Raise vbObjectError + 5160, , _
            "IntakeCase row count changed after preflight."
    End If
    If FindLastDataRow(registerWs, 6) <> lastRegisterRow Then
        Err.Raise vbObjectError + 5161, , _
            "DocumentRegister row count changed after preflight."
    End If
    RequireTableUnchanged caseWs.Range("A2:I2"), caseData, 1, 9, _
        "IntakeCase"
    RequireTableUnchanged registerWs.Range("A2:F" & lastRegisterRow), _
        registerData, UBound(registerData, 1), 6, "DocumentRegister"
    If generatedCount <> approvedCount Then
        Err.Raise vbObjectError + 5162, , _
            "Generated document count does not match the approved count."
    End If

    currentStep = "saving the generated status to IntakeCase"
    finalStatusPending = True
    caseWs.Cells(2, 9).Value2 = STATUS_DONE
    wb.Save
    finalStatusPending = False
    wdApp.NormalTemplate.Saved = True
    wdApp.Quit WD_DO_NOT_SAVE_CHANGES
    Set wdApp = Nothing
    RestoreExcelState previousScreenUpdating, previousEnableEvents
    stateCaptured = False
    MsgBox "Legal and advisory intake pack completed." & vbCrLf & _
        "Documents generated: " & generatedCount & vbCrLf & _
        "Completed folder: " & completedFolder & vbCrLf & vbCrLf & _
        "Review client identity, intake data, brand assets, DOCX, and PDF before release.", _
        vbInformation

CleanExit:
    On Error Resume Next
    If Not doc Is Nothing Then doc.Close WD_DO_NOT_SAVE_CHANGES
    If Not wdApp Is Nothing Then
        wdApp.NormalTemplate.Saved = True
        wdApp.Quit WD_DO_NOT_SAVE_CHANGES
    End If
    If stateCaptured Then _
        RestoreExcelState previousScreenUpdating, previousEnableEvents
    On Error GoTo 0
    Exit Sub

CleanFail:
    errorNumber = Err.Number
    errorDescription = Err.Description
    On Error Resume Next
    If finalStatusPending And Not caseWs Is Nothing Then
        caseWs.Cells(2, 9).Value2 = intakeStatus
        statusRecoveryMessage = vbCrLf & _
            "DONE was restored to " & intakeStatus & _
            " in memory because the final workbook save was not confirmed."
    End If
    If Not doc Is Nothing Then doc.Close WD_DO_NOT_SAVE_CHANGES
    If Not wdApp Is Nothing Then
        wdApp.NormalTemplate.Saved = True
        wdApp.Quit WD_DO_NOT_SAVE_CHANGES
    End If
    If stateCaptured Then _
        RestoreExcelState previousScreenUpdating, previousEnableEvents
    On Error GoTo 0
    MsgBox "Intake pack generation stopped while " & currentStep & "." & _
        vbCrLf & "Error " & errorNumber & ": " & errorDescription & _
        vbCrLf & IIf(Len(runFolder) > 0, _
            "Inspect the retained run folder: " & runFolder, _
            "No run folder was created.") & vbCrLf & _
        "Existing completed files were not deleted." & _
        statusRecoveryMessage, vbCritical
End Sub

Private Sub PopulateRequiredBookmarks(ByVal doc As Object, _
                                      ByVal required As Object, _
                                      ByVal intakeId As String, _
                                      ByVal clientReference As String, _
                                      ByVal clientName As String, _
                                      ByVal matterType As String, _
                                      ByVal intakeDate As String, _
                                      ByVal contactDisplay As String, _
                                      ByVal assignedProfessional As String, _
                                      ByVal intakeSummary As String, _
                                      ByVal brandImageFile As String, _
                                      ByVal brandImages As Object)
    Dim token As Variant
    For Each token In required.Keys
        Select Case CStr(token)
            Case "IntakeID": WriteTextBookmark doc, CStr(token), intakeId
            Case "ClientReference": WriteTextBookmark doc, CStr(token), clientReference
            Case "ClientName": WriteTextBookmark doc, CStr(token), clientName
            Case "MatterType": WriteTextBookmark doc, CStr(token), matterType
            Case "IntakeDateDisplay"
                WriteTextBookmark doc, CStr(token), intakeDate
            Case "ContactDisplay": WriteTextBookmark doc, CStr(token), contactDisplay
            Case "AssignedProfessional": WriteTextBookmark doc, CStr(token), assignedProfessional
            Case "IntakeSummary"
                WriteTextBookmark doc, CStr(token), intakeSummary
            Case "BrandImage"
                InsertBrandImageBookmark doc, CStr(token), _
                    brandImages(brandImageFile)
        End Select
    Next token
End Sub

Private Sub ValidateTemplate(ByVal doc As Object, _
                             ByVal required As Object, _
                             ByVal templateFile As String)
    RejectTrackedChanges doc, "template " & templateFile
    If doc.Comments.Count > 0 Then
        Err.Raise vbObjectError + 5104, , _
            "Remove comments from template " & templateFile & "."
    End If
    ValidateBookmarkContract doc, required, templateFile
End Sub

Private Sub ValidateResultBeforeSave(ByVal doc As Object, _
                                     ByVal required As Object, _
                                     ByVal documentKey As String)
    RejectTrackedChanges doc, "generated document " & documentKey
    If doc.Comments.Count > 0 Then
        Err.Raise vbObjectError + 5105, , _
            "Generated document contains comments: " & documentKey
    End If
    ValidateBookmarkContract doc, required, documentKey
End Sub

Private Sub ValidateBookmarkContract(ByVal doc As Object, _
                                     ByVal required As Object, _
                                     ByVal documentLabel As String)
    Dim token As Variant
    Dim allowed As Object
    Set allowed = AllowedBookmarkNames()
    For Each token In required.Keys
        If Not doc.Bookmarks.Exists(CStr(token)) Then
            Err.Raise vbObjectError + 5106, , _
                "Missing bookmark " & token & " in " & documentLabel & "."
        End If
        If StrComp(doc.Bookmarks(CStr(token)).Name, _
                   CStr(token), vbBinaryCompare) <> 0 Then
            Err.Raise vbObjectError + 5170, , _
                "Bookmark name case mismatch in " & _
                documentLabel & ": expected " & CStr(token) & "."
        End If
    Next token
    For Each token In allowed.Keys
        If doc.Bookmarks.Exists(CStr(token)) And _
           Not required.Exists(CStr(token)) Then
            Err.Raise vbObjectError + 5107, , _
                "Bookmark " & token & " exists but is not listed in " & _
                "RequiredBookmarks for " & documentLabel & "."
        End If
    Next token
End Sub

Private Function ParseBookmarkContract(ByVal contractText As String, _
                                       ByVal excelRow As Long) As Object
    Dim result As Object
    Dim allowed As Object
    Dim tokens As Variant
    Dim token As Variant
    Dim tokenText As String
    Set result = NewTextDictionary(vbBinaryCompare)
    Set allowed = AllowedBookmarkNames()
    tokens = Split(contractText, ";")
    For Each token In tokens
        tokenText = CStr(token)
        If Len(tokenText) = 0 Or tokenText <> Trim$(tokenText) Then
            Err.Raise vbObjectError + 5108, , _
                "RequiredBookmarks has an empty or padded token on row " & _
                excelRow & "."
        End If
        If Not allowed.Exists(tokenText) Then
            Err.Raise vbObjectError + 5109, , _
                "Unknown or incorrectly cased bookmark on row " & excelRow & _
                ": " & tokenText
        End If
        If result.Exists(tokenText) Then
            Err.Raise vbObjectError + 5110, , _
                "Duplicate bookmark token on row " & excelRow & ": " & tokenText
        End If
        result.Add tokenText, True
    Next token
    If Not result.Exists("IntakeID") Or Not result.Exists("ClientName") Then
        Err.Raise vbObjectError + 5111, , _
            "Every approved template must require IntakeID and ClientName."
    End If
    Set ParseBookmarkContract = result
End Function

Private Function AllowedBookmarkNames() As Object
    Dim result As Object
    Dim item As Variant
    Set result = NewTextDictionary(vbBinaryCompare)
    For Each item In Array("IntakeID", "ClientReference", "ClientName", _
        "MatterType", "IntakeDateDisplay", "ContactDisplay", _
        "AssignedProfessional", "IntakeSummary", "BrandImage")
        result.Add CStr(item), True
    Next item
    Set AllowedBookmarkNames = result
End Function

Private Sub ValidateBrandImageContract(ByVal required As Object, _
                                      ByVal brandImageFile As String, _
                                      ByVal excelRow As Long)
    If required.Exists("BrandImage") And Len(brandImageFile) = 0 Then
        Err.Raise vbObjectError + 5112, , _
            "BrandImageFile is required when BrandImage is listed on row " & _
            excelRow & "."
    End If
    If Not required.Exists("BrandImage") And Len(brandImageFile) > 0 Then
        Err.Raise vbObjectError + 5113, , _
            "BrandImageFile must be blank when BrandImage is not listed " & _
            "on row " & excelRow & "."
    End If
End Sub

Private Sub WriteTextBookmark(ByVal doc As Object, _
                              ByVal bookmarkName As String, _
                              ByVal replacementText As String)
    Dim targetRange As Object
    Dim styleValue As Variant
    Set targetRange = doc.Bookmarks(bookmarkName).Range
    If targetRange.Fields.Count > 0 Or _
       targetRange.ContentControls.Count > 0 Or _
       targetRange.InlineShapes.Count > 0 Then
        Err.Raise vbObjectError + 5114, , _
            "Text bookmark contains a nested object: " & bookmarkName
    End If
    RejectRangeMarkers targetRange, bookmarkName
    styleValue = targetRange.Style
    targetRange.Text = replacementText
    targetRange.Style = styleValue
    doc.Bookmarks.Add bookmarkName, targetRange
    If Not doc.Bookmarks.Exists(bookmarkName) Then
        Err.Raise vbObjectError + 5115, , _
            "Bookmark was not restored: " & bookmarkName
    End If
    If StrComp(doc.Bookmarks(bookmarkName).Range.Text, replacementText, _
       vbBinaryCompare) <> 0 Then
        Err.Raise vbObjectError + 5116, , _
            "Bookmark value differs after replacement: " & bookmarkName
    End If
End Sub

Private Sub InsertBrandImageBookmark(ByVal doc As Object, _
                                    ByVal bookmarkName As String, _
                                    ByVal imagePath As String)
    Dim targetRange As Object
    Dim picture As Object
    Set targetRange = doc.Bookmarks(bookmarkName).Range
    If targetRange.Fields.Count > 0 Or _
       targetRange.ContentControls.Count > 0 Or _
       targetRange.InlineShapes.Count > 0 Then
        Err.Raise vbObjectError + 5117, , _
            "Brand image bookmark contains a nested object."
    End If
    RejectRangeMarkers targetRange, bookmarkName
    targetRange.Text = ""
    targetRange.Collapse WD_COLLAPSE_START
    Set picture = doc.InlineShapes.AddPicture( _
        imagePath, False, True, targetRange)
    If picture.Width <= 0 Or picture.Height <= 0 Then
        Err.Raise vbObjectError + 5118, , _
            "Word inserted an invalid brand image."
    End If
    picture.LockAspectRatio = OFFICE_TRUE
    If picture.Width > 5# * POINTS_PER_CM Then _
        picture.Width = 5# * POINTS_PER_CM
    If picture.Height > 2.5 * POINTS_PER_CM Then _
        picture.Height = 2.5 * POINTS_PER_CM
    doc.Bookmarks.Add bookmarkName, picture.Range
    If doc.Bookmarks(bookmarkName).Range.InlineShapes.Count <> 1 Then
        Err.Raise vbObjectError + 5119, , _
            "Brand image bookmark does not contain one embedded image."
    End If
End Sub

Private Sub RejectRangeMarkers(ByVal targetRange As Object, _
                               ByVal bookmarkName As String)
    If InStr(1, targetRange.Text, vbCr, vbBinaryCompare) > 0 Or _
       InStr(1, targetRange.Text, Chr$(7), vbBinaryCompare) > 0 Then
        Err.Raise vbObjectError + 5120, , _
            "Bookmark includes a paragraph or cell marker: " & bookmarkName
    End If
End Sub

Private Sub RejectTrackedChanges(ByVal doc As Object, _
                                 ByVal documentLabel As String)
    If doc.TrackRevisions Then
        Err.Raise vbObjectError + 5121, , _
            "Turn off Track Changes in " & documentLabel & "."
    End If
    If CountRevisionsInAllStories(doc) > 0 Then
        Err.Raise vbObjectError + 5122, , _
            "Resolve tracked revisions in every story of " & _
            documentLabel & "."
    End If
End Sub

Private Function CountRevisionsInAllStories(ByVal doc As Object) As Long
    Dim root As Object
    Dim story As Object
    Dim total As Long
    For Each root In doc.StoryRanges
        Set story = root
        Do While Not story Is Nothing
            total = total + story.Revisions.Count
            Set story = story.NextStoryRange
        Loop
    Next root
    CountRevisionsInAllStories = total
End Function

Private Sub ValidateCaseHeaders(ByVal ws As Worksheet)
    ValidateHeaders ws, Array("IntakeID", "ClientReference", "ClientName", _
        "MatterType", "IntakeDateDisplay", "ContactDisplay", _
        "AssignedProfessional", "IntakeSummary", "IntakeStatus")
End Sub

Private Sub ValidateRegisterHeaders(ByVal ws As Worksheet)
    ValidateHeaders ws, Array("DocumentKey", "TemplateFile", _
        "OutputSuffix", "RequiredBookmarks", "BrandImageFile", _
        "DocumentStatus")
End Sub

Private Sub ValidateHeaders(ByVal ws As Worksheet, ByVal expected As Variant)
    Dim columnIndex As Long
    Dim valueText As Variant
    For columnIndex = 1 To UBound(expected) + 1
        valueText = ws.Cells(1, columnIndex).Value2
        If IsError(valueText) Or VarType(valueText) <> vbString Then
            Err.Raise vbObjectError + 5123, , _
                "Header " & ws.Cells(1, columnIndex).Address(False, False) & _
                " on " & ws.Name & " must contain exact text."
        End If
        If StrComp(CStr(valueText), CStr(expected(columnIndex - 1)), _
           vbBinaryCompare) <> 0 Then
            Err.Raise vbObjectError + 5124, , _
                "Expected header " & expected(columnIndex - 1) & _
                " in column " & columnIndex & " on " & ws.Name & "."
        End If
    Next columnIndex
End Sub

Private Sub RequireOneCaseRow(ByVal ws As Worksheet)
    Dim lastRow As Long
    lastRow = FindLastDataRow(ws, 9)
    If lastRow < 2 Then
        Err.Raise vbObjectError + 5125, , _
            "IntakeCase row 2 is missing."
    End If
    If lastRow > 2 Then
        Err.Raise vbObjectError + 5126, , _
            "Contractor logic accepts one reviewed IntakeCase row per run."
    End If
End Sub

Private Function FindLastDataRow(ByVal ws As Worksheet, _
                                 ByVal lastColumn As Long) As Long
    Dim lastCell As Range
    Set lastCell = ws.Range(ws.Cells(1, 1), _
        ws.Cells(ws.Rows.Count, lastColumn)).Find( _
        What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious, MatchCase:=False)
    If lastCell Is Nothing Then
        FindLastDataRow = 0
    Else
        FindLastDataRow = lastCell.Row
    End If
End Function

Private Function DataRowIsBlank(ByRef data As Variant, _
                                ByVal dataRow As Long, _
                                ByVal columnCount As Long) As Boolean
    Dim columnIndex As Long
    DataRowIsBlank = True
    For columnIndex = 1 To columnCount
        If IsError(data(dataRow, columnIndex)) Then
            DataRowIsBlank = False
            Exit Function
        End If
        If Len(CStr(data(dataRow, columnIndex))) > 0 Then
            DataRowIsBlank = False
            Exit Function
        End If
    Next columnIndex
End Function

Private Function ReadRequiredText(ByVal rawValue As Variant, _
                                  ByVal fieldName As String, _
                                  ByVal excelRow As Long) As String
    ReadRequiredText = ReadOptionalText(rawValue, fieldName, excelRow)
    If Len(ReadRequiredText) = 0 Then
        Err.Raise vbObjectError + 5127, , _
            fieldName & " is required on row " & excelRow & "."
    End If
End Function

Private Function ReadRequiredMultilineText(ByVal rawValue As Variant, _
                                           ByVal fieldName As String, _
                                           ByVal excelRow As Long) As String
    Dim valueText As String
    Dim meaningfulText As String
    Dim position As Long
    Dim characterCode As Long

    If IsEmpty(rawValue) Or IsError(rawValue) Then
        Err.Raise vbObjectError + 5163, , _
            fieldName & " must contain reviewed text on row " & excelRow & "."
    End If
    If VarType(rawValue) <> vbString Then
        Err.Raise vbObjectError + 5164, , _
            fieldName & " must be stored as text on row " & excelRow & "."
    End If
    valueText = CStr(rawValue)
    valueText = Replace(valueText, vbCrLf, vbLf)
    valueText = Replace(valueText, vbCr, vbLf)
    meaningfulText = Replace(valueText, vbLf, "")
    If Len(Trim$(meaningfulText)) = 0 Then
        Err.Raise vbObjectError + 5165, , _
            fieldName & " must contain meaningful text on row " & excelRow & "."
    End If
    If valueText <> Trim$(valueText) Or _
       Left$(valueText, 1) = vbLf Or Right$(valueText, 1) = vbLf Then
        Err.Raise vbObjectError + 5166, , _
            fieldName & " has outer whitespace on row " & excelRow & "."
    End If
    For position = 1 To Len(valueText)
        characterCode = AscW(Mid$(valueText, position, 1))
        If characterCode >= 0 And characterCode <= 31 And _
           characterCode <> 10 Then
            Err.Raise vbObjectError + 5167, , _
                fieldName & " contains an unsupported control character on row " & _
                excelRow & "."
        End If
    Next position
    ReadRequiredMultilineText = Replace(valueText, vbLf, vbCr)
End Function

Private Function ReadOptionalText(ByVal rawValue As Variant, _
                                  ByVal fieldName As String, _
                                  ByVal excelRow As Long) As String
    If IsEmpty(rawValue) Then
        ReadOptionalText = ""
        Exit Function
    End If
    If IsError(rawValue) Or VarType(rawValue) <> vbString Then
        Err.Raise vbObjectError + 5128, , _
            fieldName & " must be stored as text on row " & excelRow & "."
    End If
    ReadOptionalText = CStr(rawValue)
    If ReadOptionalText <> Trim$(ReadOptionalText) Then
        Err.Raise vbObjectError + 5129, , _
            fieldName & " has outer whitespace on row " & excelRow & "."
    End If
    If ContainsControlCharacter(ReadOptionalText) Then
        Err.Raise vbObjectError + 5130, , _
            fieldName & " contains a control character on row " & excelRow & "."
    End If
End Function

Private Sub ValidateIntakeStatus(ByVal statusText As String)
    If statusText <> STATUS_READY And statusText <> STATUS_HOLD And _
       statusText <> STATUS_DONE Then
        Err.Raise vbObjectError + 5131, , _
            "IntakeStatus must be exactly READY, HOLD, or DONE."
    End If
End Sub

Private Sub ValidateDocumentStatus(ByVal statusText As String, _
                                   ByVal excelRow As Long)
    If statusText <> DOC_APPROVED And statusText <> DOC_RETIRED Then
        Err.Raise vbObjectError + 5132, , _
            "DocumentStatus must be exactly APPROVED or RETIRED on row " & _
            excelRow & "."
    End If
End Sub

Private Sub ValidateKey(ByVal valueText As String, _
                        ByVal fieldName As String, _
                        ByVal excelRow As Long)
    If Len(valueText) > 80 Then
        Err.Raise vbObjectError + 5133, , _
            fieldName & " exceeds 80 characters on row " & excelRow & "."
    End If
End Sub

Private Sub ValidateFileComponent(ByVal valueText As String, _
                                  ByVal fieldName As String, _
                                  ByVal excelRow As Long)
    Dim item As Variant
    Dim baseName As String
    Dim lowerName As String
    If Len(valueText) > 100 Then
        Err.Raise vbObjectError + 5134, , _
            fieldName & " exceeds 100 characters on row " & excelRow & "."
    End If
    For Each item In Array("<", ">", ":", Chr$(34), "/", "\", _
        "|", "?", "*")
        If InStr(1, valueText, CStr(item), vbBinaryCompare) > 0 Then
            Err.Raise vbObjectError + 5135, , _
                fieldName & " contains a forbidden Windows character on row " & _
                excelRow & "."
        End If
    Next item
    If Right$(valueText, 1) = "." Or Right$(valueText, 1) = " " Then
        Err.Raise vbObjectError + 5136, , _
            fieldName & " ends with a period or space on row " & excelRow & "."
    End If
    lowerName = LCase$(valueText)
    If Right$(lowerName, 5) = ".docx" Or _
       Right$(lowerName, 4) = ".pdf" Then
        Err.Raise vbObjectError + 5137, , _
            fieldName & " must not include .docx or .pdf on row " & excelRow & "."
    End If
    baseName = valueText
    If InStr(1, baseName, ".", vbBinaryCompare) > 0 Then
        baseName = Left$(baseName, InStr(1, baseName, ".", _
            vbBinaryCompare) - 1)
    End If
    If IsReservedWindowsName(baseName) Then
        Err.Raise vbObjectError + 5138, , _
            fieldName & " uses a reserved Windows name on row " & excelRow & "."
    End If
End Sub

Private Sub ValidateDocxFileName(ByVal fileName As String, _
                                 ByVal excelRow As Long)
    ValidateAssetFileName fileName, excelRow
    If LCase$(Right$(fileName, 5)) <> ".docx" Then
        Err.Raise vbObjectError + 5139, , _
            "TemplateFile must end with .docx on row " & excelRow & "."
    End If
End Sub

Private Sub ValidateImageFileName(ByVal fileName As String, _
                                  ByVal excelRow As Long)
    Dim lowerName As String
    ValidateAssetFileName fileName, excelRow
    lowerName = LCase$(fileName)
    If Right$(lowerName, 4) <> ".png" And _
       Right$(lowerName, 4) <> ".jpg" And _
       Right$(lowerName, 5) <> ".jpeg" Then
        Err.Raise vbObjectError + 5140, , _
            "BrandImageFile must be PNG, JPG, or JPEG on row " & excelRow & "."
    End If
End Sub

Private Sub ValidateAssetFileName(ByVal fileName As String, _
                                  ByVal excelRow As Long)
    Dim item As Variant
    Dim baseName As String
    If Len(fileName) > 120 Then
        Err.Raise vbObjectError + 5168, , _
            "Asset filename exceeds 120 characters on row " & excelRow & "."
    End If
    For Each item In Array("<", ">", ":", Chr$(34), "/", "\", _
        "|", "?", "*")
        If InStr(1, fileName, CStr(item), vbBinaryCompare) > 0 Then
            Err.Raise vbObjectError + 5141, , _
                "Asset filename contains a path or wildcard on row " & _
                excelRow & "."
        End If
    Next item
    If Right$(fileName, 1) = "." Or Right$(fileName, 1) = " " Then
        Err.Raise vbObjectError + 5142, , _
            "Asset filename ends with a period or space on row " & excelRow & "."
    End If
    baseName = fileName
    If InStr(1, baseName, ".", vbBinaryCompare) > 0 Then
        baseName = Left$(baseName, InStr(1, baseName, ".", _
            vbBinaryCompare) - 1)
    End If
    If IsReservedWindowsName(baseName) Then
        Err.Raise vbObjectError + 5169, , _
            "Asset filename uses a reserved Windows name on row " & _
            excelRow & "."
    End If
End Sub

Private Sub AddUnique(ByVal values As Object, ByVal valueText As String, _
                      ByVal fieldName As String, ByVal excelRow As Long)
    If values.Exists(valueText) Then
        Err.Raise vbObjectError + 5143, , _
            "Duplicate " & fieldName & " on rows " & values(valueText) & _
            " and " & excelRow & ": " & valueText
    End If
    values.Add valueText, excelRow
End Sub

Private Function NewTextDictionary(ByVal compareMode As Long) As Object
    Dim result As Object
    Set result = CreateObject("Scripting.Dictionary")
    result.CompareMode = compareMode
    Set NewTextDictionary = result
End Function

Private Sub RequireRangeUnchanged(ByVal liveRange As Range, _
                                  ByRef snapshot As Variant, _
                                  ByVal snapshotRow As Long, _
                                  ByVal columnCount As Long, _
                                  ByVal rangeLabel As String)
    Dim liveData As Variant
    Dim columnIndex As Long
    liveData = liveRange.Value2
    For columnIndex = 1 To columnCount
        If Not ValuesExactlyEqual(snapshot(snapshotRow, columnIndex), _
           liveData(1, columnIndex)) Then
            Err.Raise vbObjectError + 5144, , _
                rangeLabel & " changed after preflight. Start a new run."
        End If
    Next columnIndex
End Sub

Private Sub RequireTableUnchanged(ByVal liveRange As Range, _
                                  ByRef snapshot As Variant, _
                                  ByVal expectedRows As Long, _
                                  ByVal expectedColumns As Long, _
                                  ByVal tableLabel As String)
    Dim liveData As Variant
    Dim rowIndex As Long
    Dim columnIndex As Long

    If liveRange.Rows.Count <> expectedRows Or _
       liveRange.Columns.Count <> expectedColumns Then
        Err.Raise vbObjectError + 5163, , _
            tableLabel & " dimensions changed after preflight."
    End If
    liveData = liveRange.Value2
    For rowIndex = 1 To expectedRows
        For columnIndex = 1 To expectedColumns
            If Not ValuesExactlyEqual(snapshot(rowIndex, columnIndex), _
               liveData(rowIndex, columnIndex)) Then
                Err.Raise vbObjectError + 5164, , _
                    tableLabel & " changed after preflight at row " & _
                    (rowIndex + 1) & ", column " & columnIndex & "."
            End If
        Next columnIndex
    Next rowIndex
End Sub

Private Function ValuesExactlyEqual(ByVal firstValue As Variant, _
                                    ByVal secondValue As Variant) As Boolean
    If IsError(firstValue) Or IsError(secondValue) Then Exit Function
    If VarType(firstValue) <> VarType(secondValue) Then Exit Function
    ValuesExactlyEqual = (StrComp(CStr(firstValue), CStr(secondValue), _
        vbBinaryCompare) = 0)
End Function

Private Sub CopyFileToSnapshot(ByVal fso As Object, _
                               ByVal sourcePath As String, _
                               ByVal snapshotPath As String, _
                               ByVal fileLabel As String)
    Dim sourceSize As Variant
    Dim sourceModified As Date
    Dim failureText As String
    RequireNonemptyFile sourcePath, fileLabel
    RequireTargetAbsent snapshotPath
    On Error GoTo CopyFailed
    sourceSize = fso.GetFile(sourcePath).Size
    sourceModified = fso.GetFile(sourcePath).DateLastModified
    fso.CopyFile sourcePath, snapshotPath, False
    RequireNonemptyFile snapshotPath, fileLabel & " snapshot"
    If fso.GetFile(snapshotPath).Size <> sourceSize Then
        Err.Raise vbObjectError + 5145, , _
            "Snapshot size differs for " & fileLabel & "."
    End If
    If fso.GetFile(sourcePath).Size <> sourceSize Or _
       fso.GetFile(sourcePath).DateLastModified <> sourceModified Then
        Err.Raise vbObjectError + 5146, , _
            "Source changed while snapshotting " & fileLabel & "."
    End If
    Exit Sub
CopyFailed:
    failureText = Err.Description
    Err.Raise vbObjectError + 5147, , _
        "Could not snapshot " & fileLabel & ": " & failureText
End Sub

Private Function CreateRunFolder(ByVal fso As Object, _
                                 ByVal outputRoot As String, _
                                 ByVal intakeId As String) As String
    Dim baseName As String
    Dim candidate As String
    Dim suffix As Long
    baseName = "Run_" & intakeId & "_" & Format$(Now, "yyyymmdd_hhnnss")
    candidate = JoinPath(outputRoot, baseName)
    Do While fso.FolderExists(candidate)
        suffix = suffix + 1
        candidate = JoinPath(outputRoot, baseName & "_" & _
            Format$(suffix, "000"))
    Loop
    fso.CreateFolder candidate
    CreateRunFolder = candidate
End Function

Private Sub RequireWritableMacroWorkbook(ByVal wb As Workbook)
    If Len(wb.Path) = 0 Or LCase$(Right$(wb.Name, 5)) <> ".xlsm" Then
        Err.Raise vbObjectError + 5148, , _
            "Save this workbook as an Excel Macro-Enabled Workbook (.xlsm)."
    End If
    If wb.ReadOnly Then
        Err.Raise vbObjectError + 5149, , _
            "The workbook is read-only; DONE cannot be saved."
    End If
End Sub

Private Function RequireWorksheet(ByVal wb As Workbook, _
                                  ByVal sheetName As String) As Worksheet
    On Error GoTo MissingSheet
    Set RequireWorksheet = wb.Worksheets(sheetName)
    Exit Function
MissingSheet:
    Err.Raise vbObjectError + 5150, , _
        "Missing worksheet: " & sheetName
End Function

Private Sub EnsureFolder(ByVal folderPath As String)
    If FolderExistsStrict(folderPath) Then Exit Sub
    On Error GoTo CreateFailed
    MkDir folderPath
    Exit Sub
CreateFailed:
    Err.Raise vbObjectError + 5151, , _
        "Could not create folder: " & folderPath & ". " & Err.Description
End Sub

Private Sub RequireFolder(ByVal folderPath As String, _
                          ByVal folderLabel As String)
    If Not FolderExistsStrict(folderPath) Then
        Err.Raise vbObjectError + 5152, , _
            "Missing " & folderLabel & ": " & folderPath
    End If
End Sub

Private Sub RequireTargetAbsent(ByVal filePath As String)
    If FileExistsStrict(filePath) Then
        Err.Raise vbObjectError + 5153, , _
            "Refusing to overwrite existing file: " & filePath
    End If
End Sub

Private Sub RequireNonemptyFile(ByVal filePath As String, _
                                ByVal fileLabel As String)
    If Not FileExistsStrict(filePath) Then
        Err.Raise vbObjectError + 5154, , _
            "Missing " & fileLabel & ": " & filePath
    End If
    On Error GoTo InspectFailed
    If FileLen(filePath) <= 0 Then
        Err.Raise vbObjectError + 5155, , _
            "Empty " & fileLabel & ": " & filePath
    End If
    Exit Sub
InspectFailed:
    Err.Raise vbObjectError + 5156, , _
        "Could not inspect " & fileLabel & ": " & filePath & _
        ". " & Err.Description
End Sub

Private Function FileExistsStrict(ByVal filePath As String) As Boolean
    On Error GoTo CheckFailed
    FileExistsStrict = (Len(Dir$(filePath, _
        vbNormal Or vbHidden Or vbSystem Or vbReadOnly)) > 0)
    Exit Function
CheckFailed:
    Err.Raise vbObjectError + 5157, , _
        "Could not check file path: " & filePath & ". " & Err.Description
End Function

Private Function FolderExistsStrict(ByVal folderPath As String) As Boolean
    Dim resultText As String
    On Error GoTo CheckFailed
    resultText = Dir$(folderPath, vbDirectory)
    If Len(resultText) > 0 Then
        FolderExistsStrict = _
            ((GetAttr(folderPath) And vbDirectory) = vbDirectory)
    End If
    Exit Function
CheckFailed:
    Err.Raise vbObjectError + 5158, , _
        "Could not check folder: " & folderPath & ". " & Err.Description
End Function

Private Function JoinPath(ByVal parentPath As String, _
                          ByVal childName As String) As String
    If Right$(parentPath, 1) = "\" Then
        JoinPath = parentPath & childName
    Else
        JoinPath = parentPath & "\" & childName
    End If
End Function

Private Function ContainsControlCharacter(ByVal valueText As String) As Boolean
    Dim index As Long
    Dim code As Long
    For index = 1 To Len(valueText)
        code = AscW(Mid$(valueText, index, 1))
        If code >= 0 And code <= 31 Then
            ContainsControlCharacter = True
            Exit Function
        End If
    Next index
End Function

Private Function IsReservedWindowsName(ByVal baseName As String) As Boolean
    Dim upperName As String
    Dim suffixText As String
    Dim suffixCode As Long
    upperName = UCase$(baseName)
    Select Case upperName
        Case "CON", "PRN", "AUX", "NUL", "CLOCK$"
            IsReservedWindowsName = True
            Exit Function
    End Select
    If Len(upperName) >= 4 Then
        If Left$(upperName, 3) = "COM" Or Left$(upperName, 3) = "LPT" Then
            suffixText = Mid$(upperName, 4)
            If Len(suffixText) = 1 Then
                suffixCode = AscW(suffixText)
                If (suffixCode >= AscW("1") And suffixCode <= AscW("9")) Or _
                   suffixText = ChrW$(&HB9) Or suffixText = ChrW$(&HB2) Or _
                   suffixText = ChrW$(&HB3) Then
                    IsReservedWindowsName = True
                End If
            End If
        End If
    End If
End Function

Private Sub RestoreExcelState(ByVal screenUpdatingValue As Boolean, _
                              ByVal enableEventsValue As Boolean)
    Application.EnableEvents = enableEventsValue
    Application.ScreenUpdating = screenUpdatingValue
End Sub

The example uses Word’s documented bookmark checks, DOCX saving, and PDF export.

Review the generated intake pack before operational use

Case identity

Match IntakeID, ClientReference, ClientName, MatterType, intake date, assigned professional, and the source record.

Complete document set

Confirm that every APPROVED register row produced one nonempty DOCX/PDF pair and no RETIRED row produced a file.

Purpose and wording

Check that each template serves the intended intake-stage purpose and does not overstate acceptance, clearance, advice, or engagement.

Summary and contact

Review the multiline IntakeSummary, optional ContactDisplay, names, dates, punctuation, missing fields, and sensitive details.

Branding and metadata

Verify the optional brand image, headers, footers, page layout, links, document properties, and PDF metadata before distribution.

Decision records

Record conflict clearance, client acceptance, engagement approval, signatures, recipients, delivery, retention, and later changes separately.

Know what the free example does not guarantee

No conflict clearance

The macro does not search names, resolve matches, assess conflicts, or approve a matter.

No identity verification

It does not authenticate a person, entity, document, email address, authority, or beneficial ownership.

No engagement creation

Generation does not prove acceptance, signature, consent, advice, scope, or a binding professional relationship.

No cryptographic snapshot

Size and modification-time checks help detect ordinary changes but do not provide signed hashes or a chain of custody.

No atomic pack commit

Each DOCX/PDF pair and the final Excel DONE status are separate operations. Reconcile the retained run folder after a failure.

No automatic compliance

Local processing can support a policy, but the macro does not establish regulatory, contractual, ethical, privacy, or records compliance.

Use Contractor for one intake case and several documents

DocxForge Pro Contractor starts with one reviewed case and creates several different documents from different Word templates. That is the intake-pack architecture described here.

Where Contractor fits

Use it when one intake case needs an acknowledgment, conflict summary, information request, consultation brief, or other distinct documents. A many-row, one-template intake batch is a separate Factory workflow.

Contractor: one reviewed intake case

Review shared case data, define the document structure, choose the different templates, and confirm local output settings.

DocxForge Pro Contractor case data screen for a legal or advisory intake case
Case Data: review the shared client and intake values.
DocxForge Pro Contractor structure screen for an intake document pack
Structure: organize the different intake-stage documents.
DocxForge Pro Contractor documents screen with different Word templates
Documents: select the approved Word template for each output.
DocxForge Pro Contractor settings screen for local intake pack output
Settings: confirm local filenames, folders, and output options.
Create a controlled intake document pack with Contractor7 days free, then $38 every 3 months • 14-day refund after purchase.
One intake caseDifferent templatesLocal processingDOCX + PDF
Start Free 7-Day Trial

Frequently asked questions

Is this the same workflow as generating one legal intake document per Excel row?

No. This article uses Contractor logic: one reviewed intake case feeds several different approved Word templates. For many independent intake rows using one standard template, use a Factory workflow instead.

Which documents can belong to an intake pack?

Examples include an intake acknowledgment, conflict-check summary, information request checklist, consultation brief, and internal routing sheet. Include only approved documents that belong at the intake stage.

Can different templates require different bookmarks?

Yes. Each DocumentRegister row declares its exact semicolon-separated RequiredBookmarks contract. Every approved template must require IntakeID and ClientName; other allowed bookmarks are included only where needed.

Can IntakeSummary contain several paragraphs?

Yes. The macro accepts ordinary line breaks, normalizes them for Word, and rejects a value made only of spaces or line breaks. Tabs and unsupported control characters are blocked.

Does DONE mean the firm accepted the client or cleared conflicts?

No. DONE confirms that the approved document set was generated and the workbook status was saved. Conflict clearance, identity checks, eligibility, engagement, advice, signatures, and release remain separate controlled decisions.

What does the optional BrandImage do?

It embeds an approved local logo or other branding asset when a template lists BrandImage. It is not a signature, digital seal, proof of authority, or compliance approval.

Keep one intake case consistent across several approved documentsUse local Word templates with Contractor. 7 days free, then $38 every 3 months • 14-day refund.
Reviewed case dataDifferent templatesEditable DOCXFinal PDF
Start Free 7-Day Trial