Fixes & Troubleshooting

Fix: Word Mail Merge Not Updating Images on PDF Export

Separate a stale PDF-export result from a bad source path, then embed the verified record image in the final merged document before Word creates the PDF.

Final merged record
Verified photo file
Embedded image
DOCX + PDF review
A correct Preview Results screen is not release evidence. Inspect the separate merged DOCX and the exported PDF for records with visibly different images.

Quick answer: resolve the image in the final document before PDF export

If the Word main document or preview looks right but the PDF is stale, blank, or missing the image, test the final merged record. Update and embed the image there before saving and exporting. For a repeatable batch, avoid depending on an image field at export time: insert the verified record file directly into the merged output.

Reliable order

Validate the record and image file → merge exactly one included record → confirm Word created a new document → insert and embed the verified image → update remaining fields → save DOCX → export PDF → review both artifacts.

Match the symptom to the stage that can produce it

Preview is right, PDF repeats an earlier photo

The preview is not the final export state. Inspect the generated record for a linked or cached image result before blaming the PDF viewer.

DOCX opens correctly only near the source folder

The image may still depend on a local or network link. Test a copy without access to the original image path.

PDF contains an empty image area

The file path may have become unavailable, the field result may be blank, or export may have run before the graphic was resolved.

Only later records fail

Check whether the batch is updating one shared field result instead of generating and finalizing one record at a time.

Header image is stale

Updating only Document.Fields can miss fields in headers, footers, and other stories. Audit the actual placement.

Word and PDF both show the wrong photo

This is earlier than PDF export. Verify the Excel value, filename, selected record, and merge lifecycle first.

Separate source, merge, embedding, and export failures

1. Source contract

Confirm that each READY record has the intended PhotoFile, unique RecordID, unique OutputName, and no hidden whitespace.

2. Merge boundary

Confirm that the record is included and that Word creates exactly one new document for the selected source row.

3. Image ownership

Confirm that the final document contains an embedded graphic, not an unresolved path that only works on the author’s computer.

4. PDF boundary

Export only after the final document is saved and its remaining fields have updated successfully.

Different from the repeated-image diagnosis

If all records already show the same image in generated DOCX files, fix the data and merge lifecycle first. This article addresses the next boundary: preserving the correct final graphic through PDF export.

Prove the repair manually with three records

Use red, green, and blue test images with the RecordID printed inside each file. A visually obvious pilot is faster to diagnose than three similar portraits.

Merge to a new document

Use Finish & Merge → Edit Individual Documents. Do not approve the result from Preview Results alone.

Update the final image field

If using INCLUDEPICTURE for the manual test, update that field in the merged output and verify the correct record image.

Embed only the verified image

After confirming it, unlink only that field so its current graphic becomes static. Other fields may still need to remain fields.

Save before export

Save the merged DOCX, close and reopen a copy if needed, then export the PDF from the verified result.

Remove source access

Open a copy where the original Photos folder is unavailable. The image should remain visible if it is embedded.

Inspect both artifacts

Compare RecordID, image identity, proportions, placement, headers, page count, and the PDF at normal zoom and print size.

Use a literal image slot for the automated repair

Save the Word main document as .docm and connect it to the Excel source. Keep ordinary text merge fields, but replace the record-specific INCLUDEPICTURE field with exactly one literal marker:

Required marker

[[PHOTO]]

The VBA helper rejects templates and merged outputs containing INCLUDEPICTURE fields. It locates the single literal marker across Word story ranges, verifies that it does not overlap a field, content control, or existing image, and inserts the current record’s checked file directly.

Keep the slot inline

Place the marker in a normal paragraph or table cell where an inline image belongs. Avoid a floating shape placeholder.

Control maximum size

The example preserves aspect ratio and only shrinks images beyond 432 × 288 points. Adjust the constants to the tested layout.

Prepare the Excel and folder contract

The connected Excel source needs four exact field names. Store all four as text and do not silently trim or normalize values.

Required Excel fields

RecordID — stable identifier; PhotoFile — filename only; OutputName — filename stem without extension; RecordStatus — exactly READY, HOLD, or DONE.

Photos folder

Place nonempty PNG, JPG, or JPEG files in Photos beside the saved .docm main document.

GeneratedImageExports folder

The helper creates this output folder beside the main document when it does not exist.

Unique values

READY rows require unique RecordID and OutputName values without forbidden Windows characters or reserved names.

One active writer

Do not run concurrent writers against the same output folder. The existence checks do not make the DOCX/PDF pair atomic.

Free Word VBA helper: embed the record image before PDF export

Run this macro from the saved .docm Mail Merge main document. It preflights every source row and output name, merges one included READY record at a time, inserts the verified PhotoFile at [[PHOTO]], saves staged DOCX/PDF files, and commits them without ordinary overwrite.

Two-pass validation

All READY records, images, names, and existing targets are checked before the first merge. Critical values are checked again before each record runs.

New-document proof

The macro verifies that Mail Merge created exactly one new document and did not leave the main document active.

Explicit embedded image

The file is inserted with LinkToFile:=False and SaveWithDocument:=True, then fitted without enlarging small images.

Fields updated before export

Remaining fields across Word story ranges must update successfully before the staged DOCX and PDF are created.

Staged output

Both files are created under a unique run folder and checked for nonzero size before their final moves.

Evidence retained on failure

Committed files are never deleted automatically. Staging files remain available for inspection after a failed run.

Word VBA — verified image before PDF exportStatic example
Option Explicit

Private Const PHOTO_TOKEN As String = "[[PHOTO]]"
Private Const PHOTO_FOLDER_NAME As String = "Photos"
Private Const OUTPUT_FOLDER_NAME As String = "GeneratedImageExports"
Private Const READY_STATUS As String = "READY"
Private Const HOLD_STATUS As String = "HOLD"
Private Const DONE_STATUS As String = "DONE"
Private Const FILE_ATTRIBUTES As Long = 39
Private Const FOLDER_ATTRIBUTES As Long = 22
Private Const WD_FIELD_INCLUDE_PICTURE As Long = 67
Private Const MAX_PHOTO_WIDTH_POINTS As Single = 432!
Private Const MAX_PHOTO_HEIGHT_POINTS As Single = 288!

Public Sub MergeRecordsWithEmbeddedPhotosBeforePdf()
    Dim mainDoc As Document
    Dim mergedDoc As Document
    Dim dataSource As MailMergeDataSource
    Dim recordIds As Object
    Dim outputNames As Object
    Dim recordNumbers() As Long
    Dim verifiedRecordIds() As String
    Dim verifiedPhotoPaths() As String
    Dim verifiedOutputNames() As String
    Dim recordCount As Long
    Dim recordNumber As Long
    Dim readyCount As Long
    Dim itemIndex As Long
    Dim documentCountBefore As Long
    Dim photoFolder As String
    Dim outputFolder As String
    Dim runFolder As String
    Dim tempDocxPath As String
    Dim tempPdfPath As String
    Dim finalDocxPath As String
    Dim finalPdfPath As String
    Dim recordId As String
    Dim photoFile As String
    Dim photoPath As String
    Dim outputName As String
    Dim statusText As String
    Dim oldFirstRecord As Long
    Dim oldLastRecord As Long
    Dim oldActiveRecord As Long
    Dim oldDisplayAlerts As Long
    Dim oldScreenUpdating As Boolean
    Dim dataSourceReady As Boolean
    Dim currentStep As String
    Dim errorNumber As Long
    Dim errorDescription As String

    On Error GoTo CleanFail

    Set mainDoc = ActiveDocument
    oldDisplayAlerts = Application.DisplayAlerts
    oldScreenUpdating = Application.ScreenUpdating
    Application.DisplayAlerts = wdAlertsNone
    Application.ScreenUpdating = False

    currentStep = "checking the saved Word mail merge main document"
    If Len(mainDoc.Path) = 0 Then
        Err.Raise vbObjectError + 4500, , _
            "Save the Word mail merge main document as .docm before running the macro."
    End If
    If LCase$(Right$(mainDoc.Name, 5)) <> ".docm" Then
        Err.Raise vbObjectError + 4501, , _
            "The Word mail merge main document must be saved as .docm."
    End If
    If mainDoc.MailMerge.State <> wdMainAndDataSource Then
        Err.Raise vbObjectError + 4502, , _
            "Connect the Word main document to its Excel data source first."
    End If
    If CountLiteralTokenInStories(mainDoc, PHOTO_TOKEN) <> 1 Then
        Err.Raise vbObjectError + 4503, , _
            "The main document must contain exactly one literal [[PHOTO]] token."
    End If
    If CountFieldsByType(mainDoc, WD_FIELD_INCLUDE_PICTURE) > 0 Then
        Err.Raise vbObjectError + 4504, , _
            "Remove INCLUDEPICTURE fields from this workflow. Use one literal [[PHOTO]] token."
    End If

    Set dataSource = mainDoc.MailMerge.DataSource
    dataSourceReady = True
    oldFirstRecord = dataSource.FirstRecord
    oldLastRecord = dataSource.LastRecord
    oldActiveRecord = dataSource.ActiveRecord

    currentStep = "checking the required Excel fields"
    RequireDataField dataSource, "RecordID"
    RequireDataField dataSource, "PhotoFile"
    RequireDataField dataSource, "OutputName"
    RequireDataField dataSource, "RecordStatus"

    recordCount = dataSource.RecordCount
    If recordCount = -1 Then
        Err.Raise vbObjectError + 4505, , _
            "Word returned an unknown record count. Reconnect the Excel source before retrying."
    End If
    If recordCount < 1 Then
        Err.Raise vbObjectError + 4506, , _
            "No records were found in the connected Excel source."
    End If

    currentStep = "checking the controlled folders"
    photoFolder = JoinPath(mainDoc.Path, PHOTO_FOLDER_NAME)
    RequireExistingFolder photoFolder, "Photos"
    outputFolder = JoinPath(mainDoc.Path, OUTPUT_FOLDER_NAME)
    EnsureOutputFolder outputFolder

    ReDim recordNumbers(1 To recordCount)
    ReDim verifiedRecordIds(1 To recordCount)
    ReDim verifiedPhotoPaths(1 To recordCount)
    ReDim verifiedOutputNames(1 To recordCount)

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

    ' Pass 1 validates every source row and target before Mail Merge creates output.
    currentStep = "preflighting the mail merge data source"
    For recordNumber = 1 To recordCount
        dataSource.ActiveRecord = recordNumber
        statusText = ReadExactDataField( _
            dataSource, "RecordStatus", recordNumber, True)

        Select Case statusText
            Case READY_STATUS
                If Not dataSource.Included Then
                    Err.Raise vbObjectError + 4507, , _
                        "READY record " & recordNumber & _
                        " is excluded in Mail Merge Recipients."
                End If

                recordId = ReadExactDataField( _
                    dataSource, "RecordID", recordNumber, False)
                photoFile = ReadExactDataField( _
                    dataSource, "PhotoFile", recordNumber, False)
                outputName = ReadExactDataField( _
                    dataSource, "OutputName", recordNumber, False)

                ValidateIdentifier recordId, "RecordID", recordNumber
                ValidateFileStem outputName, "OutputName", recordNumber
                If LCase$(Right$(outputName, 5)) = ".docx" Or _
                   LCase$(Right$(outputName, 4)) = ".pdf" Then
                    Err.Raise vbObjectError + 4544, , _
                        "OutputName must be a filename stem without .docx or .pdf " & _
                        "at record " & recordNumber & "."
                End If
                ValidatePhotoFileName photoFile, recordNumber

                If recordIds.Exists(recordId) Then
                    Err.Raise vbObjectError + 4508, , _
                        "Duplicate RecordID in records " & recordIds(recordId) & _
                        " and " & recordNumber & ": " & recordId
                End If
                recordIds.Add recordId, recordNumber

                If outputNames.Exists(outputName) Then
                    Err.Raise vbObjectError + 4509, , _
                        "Duplicate OutputName in records " & outputNames(outputName) & _
                        " and " & recordNumber & ": " & outputName
                End If
                outputNames.Add outputName, recordNumber

                photoPath = JoinPath(photoFolder, photoFile)
                ValidatePhotoFile photoPath, recordNumber

                finalDocxPath = JoinPath(outputFolder, outputName & ".docx")
                finalPdfPath = JoinPath(outputFolder, outputName & ".pdf")
                RequireTargetAbsent finalDocxPath
                RequireTargetAbsent finalPdfPath

                readyCount = readyCount + 1
                recordNumbers(readyCount) = recordNumber
                verifiedRecordIds(readyCount) = recordId
                verifiedPhotoPaths(readyCount) = photoPath
                verifiedOutputNames(readyCount) = outputName

            Case HOLD_STATUS, DONE_STATUS
                ' These records remain outside this run.
            Case Else
                Err.Raise vbObjectError + 4510, , _
                    "RecordStatus must be exactly READY, HOLD, or DONE at record " & _
                    recordNumber & "."
        End Select
    Next recordNumber

    If readyCount = 0 Then
        Err.Raise vbObjectError + 4511, , _
            "No included records with RecordStatus READY were found."
    End If

    currentStep = "creating the run-specific staging folder"
    runFolder = CreateRunFolder(outputFolder)

    ' Pass 2 merges one validated record, embeds its verified image, then exports PDF.
    For itemIndex = 1 To readyCount
        recordNumber = recordNumbers(itemIndex)
        recordId = verifiedRecordIds(itemIndex)
        photoPath = verifiedPhotoPaths(itemIndex)
        outputName = verifiedOutputNames(itemIndex)

        dataSource.ActiveRecord = recordNumber
        If Not dataSource.Included Then
            Err.Raise vbObjectError + 4512, , _
                "READY record " & recordNumber & _
                " became excluded after preflight."
        End If
        If ReadExactDataField(dataSource, "RecordStatus", recordNumber, True) <> _
           READY_STATUS Then
            Err.Raise vbObjectError + 4513, , _
                "RecordStatus changed after preflight at record " & recordNumber & "."
        End If
        If ReadExactDataField(dataSource, "RecordID", recordNumber, False) <> _
           recordId Then
            Err.Raise vbObjectError + 4514, , _
                "RecordID changed after preflight at record " & recordNumber & "."
        End If
        If JoinPath(photoFolder, ReadExactDataField( _
            dataSource, "PhotoFile", recordNumber, False)) <> photoPath Then
            Err.Raise vbObjectError + 4515, , _
                "PhotoFile changed after preflight at record " & recordNumber & "."
        End If
        If ReadExactDataField(dataSource, "OutputName", recordNumber, False) <> _
           outputName Then
            Err.Raise vbObjectError + 4516, , _
                "OutputName changed after preflight at record " & recordNumber & "."
        End If
        ValidatePhotoFile photoPath, recordNumber

        tempDocxPath = JoinPath(runFolder, outputName & ".docx")
        tempPdfPath = JoinPath(runFolder, outputName & ".pdf")
        finalDocxPath = JoinPath(outputFolder, outputName & ".docx")
        finalPdfPath = JoinPath(outputFolder, outputName & ".pdf")

        currentStep = "merging record " & recordNumber
        Set mergedDoc = Nothing
        mainDoc.Activate
        documentCountBefore = Documents.Count

        With mainDoc.MailMerge
            .Destination = wdSendToNewDocument
            .SuppressBlankLines = True
            .DataSource.FirstRecord = recordNumber
            .DataSource.LastRecord = recordNumber
            .DataSource.ActiveRecord = recordNumber
            .Execute Pause:=False
        End With

        If Documents.Count <> documentCountBefore + 1 Then
            Err.Raise vbObjectError + 4517, , _
                "Mail Merge did not create exactly one new document for record " & _
                recordNumber & "."
        End If

        Set mergedDoc = ActiveDocument
        If mergedDoc Is mainDoc Then
            Err.Raise vbObjectError + 4518, , _
                "The active document is still the mail merge main document."
        End If

        currentStep = "embedding the verified image for record " & recordNumber
        If CountFieldsByType(mergedDoc, WD_FIELD_INCLUDE_PICTURE) > 0 Then
            Err.Raise vbObjectError + 4519, , _
                "The merged document still contains an INCLUDEPICTURE field."
        End If
        ReplaceSinglePhotoToken mergedDoc, photoPath, recordId
        UpdateFieldsInAllStories mergedDoc

        currentStep = "saving staged DOCX and PDF for record " & recordNumber
        mergedDoc.SaveAs2 _
            FileName:=tempDocxPath, _
            FileFormat:=wdFormatXMLDocument, _
            AddToRecentFiles:=False
        mergedDoc.ExportAsFixedFormat _
            OutputFileName:=tempPdfPath, _
            ExportFormat:=wdExportFormatPDF, _
            OpenAfterExport:=False
        mergedDoc.Close SaveChanges:=wdDoNotSaveChanges
        Set mergedDoc = Nothing
        mainDoc.Activate

        ValidateCreatedFile tempDocxPath, "staged DOCX"
        ValidateCreatedFile tempPdfPath, "staged PDF"

        currentStep = "committing DOCX and PDF for record " & recordNumber
        RequireTargetAbsent finalDocxPath
        RequireTargetAbsent finalPdfPath
        Name tempDocxPath As finalDocxPath
        Name tempPdfPath As finalPdfPath
    Next itemIndex

    RemoveEmptyRunFolder runFolder
    runFolder = vbNullString
    RestoreMailMergeState dataSource, oldFirstRecord, oldLastRecord, _
        oldActiveRecord, dataSourceReady
    Application.DisplayAlerts = oldDisplayAlerts
    Application.ScreenUpdating = oldScreenUpdating

    MsgBox readyCount & _
        " record(s) generated with an explicitly embedded photo before PDF export.", _
        vbInformation, "Mail Merge image export complete"
    Exit Sub

CleanFail:
    errorNumber = Err.Number
    errorDescription = Err.Description

    On Error Resume Next
    If Not mergedDoc Is Nothing Then
        mergedDoc.Close SaveChanges:=wdDoNotSaveChanges
    End If
    RestoreMailMergeState dataSource, oldFirstRecord, oldLastRecord, _
        oldActiveRecord, dataSourceReady
    If Not mainDoc Is Nothing Then mainDoc.Activate
    Application.DisplayAlerts = oldDisplayAlerts
    Application.ScreenUpdating = oldScreenUpdating
    On Error GoTo 0

    MsgBox "The run stopped while " & currentStep & "." & vbCrLf & _
        "Error " & errorNumber & ": " & errorDescription & vbCrLf & _
        "Files already committed were not deleted. Run-specific staging files " & _
        "were left for inspection: " & runFolder, _
        vbCritical, "Mail Merge image export stopped"
End Sub

Private Sub RequireDataField( _
    ByVal dataSource As MailMergeDataSource, _
    ByVal fieldName As String)

    Dim actualName As String

    On Error GoTo MissingField
    actualName = dataSource.DataFields(fieldName).Name
    On Error GoTo 0
    Exit Sub

MissingField:
    On Error GoTo 0
    Err.Raise vbObjectError + 4520, , _
        "Required Excel field not found: " & fieldName
End Sub

Private Function ReadExactDataField( _
    ByVal dataSource As MailMergeDataSource, _
    ByVal fieldName As String, _
    ByVal recordNumber As Long, _
    ByVal allowBlank As Boolean) As String

    Dim valueText As String

    On Error GoTo ReadFailed
    valueText = CStr(dataSource.DataFields(fieldName).Value)
    On Error GoTo 0

    If Not allowBlank And Len(valueText) = 0 Then
        Err.Raise vbObjectError + 4521, , _
            fieldName & " is blank at record " & recordNumber & "."
    End If
    If valueText <> Trim$(valueText) Then
        Err.Raise vbObjectError + 4522, , _
            fieldName & " has leading or trailing whitespace at record " & _
            recordNumber & "."
    End If
    If ContainsControlCharacter(valueText) Then
        Err.Raise vbObjectError + 4523, , _
            fieldName & " contains a control character at record " & _
            recordNumber & "."
    End If

    ReadExactDataField = valueText
    Exit Function

ReadFailed:
    On Error GoTo 0
    Err.Raise vbObjectError + 4524, , _
        "Could not read " & fieldName & " at record " & recordNumber & "."
End Function

Private Sub ValidateIdentifier( _
    ByVal valueText As String, _
    ByVal fieldName As String, _
    ByVal recordNumber As Long)

    Dim index As Long
    Dim character As String

    For index = 1 To Len(valueText)
        character = Mid$(valueText, index, 1)
        If Not (character Like "[A-Za-z0-9_-]") Then
            Err.Raise vbObjectError + 4530, , _
                fieldName & " may contain only letters, digits, underscore, " & _
                "and hyphen at record " & recordNumber & "."
        End If
    Next index
End Sub

Private Sub ValidateFileStem( _
    ByVal fileStem As String, _
    ByVal fieldName As String, _
    ByVal recordNumber As Long)

    Dim forbidden As Variant
    Dim item As Variant
    Dim baseName As String
    Dim dotPosition As Long

    forbidden = Array("\", "/", ":", "*", "?", Chr$(34), "<", ">", "|")
    For Each item In forbidden
        If InStr(1, fileStem, CStr(item), vbBinaryCompare) > 0 Then
            Err.Raise vbObjectError + 4531, , _
                fieldName & " contains a forbidden Windows character at record " & _
                recordNumber & "."
        End If
    Next item

    If Len(fileStem) > 120 Then
        Err.Raise vbObjectError + 4532, , _
            fieldName & " exceeds 120 characters at record " & recordNumber & "."
    End If
    If Right$(fileStem, 1) = "." Or Right$(fileStem, 1) = " " Then
        Err.Raise vbObjectError + 4533, , _
            fieldName & " cannot end with a dot or space at record " & _
            recordNumber & "."
    End If
    If ContainsControlCharacter(fileStem) Then
        Err.Raise vbObjectError + 4534, , _
            fieldName & " contains a control character at record " & _
            recordNumber & "."
    End If

    baseName = fileStem
    dotPosition = InStr(1, baseName, ".", vbBinaryCompare)
    If dotPosition > 0 Then baseName = Left$(baseName, dotPosition - 1)
    If IsReservedWindowsName(baseName) Then
        Err.Raise vbObjectError + 4535, , _
            fieldName & " uses a reserved Windows name at record " & _
            recordNumber & "."
    End If
End Sub

Private Sub ValidatePhotoFileName( _
    ByVal photoFile As String, _
    ByVal recordNumber As Long)

    Dim extensionText As String
    Dim dotPosition As Long

    ValidateFileStem photoFile, "PhotoFile", recordNumber
    dotPosition = InStrRev(photoFile, ".")
    If dotPosition <= 1 Or dotPosition = Len(photoFile) Then
        Err.Raise vbObjectError + 4540, , _
            "PhotoFile requires a PNG, JPG, or JPEG extension at record " & _
            recordNumber & "."
    End If

    extensionText = LCase$(Mid$(photoFile, dotPosition + 1))
    Select Case extensionText
        Case "png", "jpg", "jpeg"
        Case Else
            Err.Raise vbObjectError + 4541, , _
                "PhotoFile must use PNG, JPG, or JPEG at record " & _
                recordNumber & "."
    End Select
End Sub

Private Sub ValidatePhotoFile( _
    ByVal photoPath As String, _
    ByVal recordNumber As Long)

    If Not FileExistsStrict(photoPath) Then
        Err.Raise vbObjectError + 4542, , _
            "Photo file was not found at record " & recordNumber & _
            ": " & photoPath
    End If
    If FileLen(photoPath) <= 0 Then
        Err.Raise vbObjectError + 4543, , _
            "Photo file is empty at record " & recordNumber & _
            ": " & photoPath
    End If
End Sub

Private Sub ReplaceSinglePhotoToken( _
    ByVal targetDoc As Document, _
    ByVal verifiedPhotoPath As String, _
    ByVal recordId As String)

    Dim firstStory As Range
    Dim currentStory As Range
    Dim targetRange As Range
    Dim picture As InlineShape
    Dim foundCount As Long

    foundCount = CountLiteralTokenInStories(targetDoc, PHOTO_TOKEN)
    If foundCount <> 1 Then
        Err.Raise vbObjectError + 4550, , _
            "The merged document must contain exactly one literal [[PHOTO]] token; " & _
            "found " & foundCount & "."
    End If

    For Each firstStory In targetDoc.StoryRanges
        Set currentStory = firstStory
        Do While Not currentStory Is Nothing
            Set targetRange = currentStory.Duplicate
            With targetRange.Find
                .ClearFormatting
                .Replacement.ClearFormatting
                .Text = PHOTO_TOKEN
                .Forward = True
                .Wrap = wdFindStop
                .Format = False
                .MatchCase = True
                .MatchWildcards = False
                If .Execute Then
                    If targetRange.Fields.Count > 0 Or _
                       targetRange.ContentControls.Count > 0 Or _
                       targetRange.InlineShapes.Count > 0 Then
                        Err.Raise vbObjectError + 4551, , _
                            "The [[PHOTO]] token overlaps a field, content control, or image."
                    End If

                    targetRange.Text = vbNullString
                    targetRange.Collapse Direction:=wdCollapseStart
                    Set picture = targetDoc.InlineShapes.AddPicture( _
                        FileName:=verifiedPhotoPath, _
                        LinkToFile:=False, _
                        SaveWithDocument:=True, _
                        Range:=targetRange)
                    picture.LockAspectRatio = msoTrue
                    FitInlinePicture picture, MAX_PHOTO_WIDTH_POINTS, _
                        MAX_PHOTO_HEIGHT_POINTS
                    picture.AlternativeText = "Photo for record " & recordId
                    Exit Sub
                End If
            End With
            Set currentStory = currentStory.NextStoryRange
        Loop
    Next firstStory

    Err.Raise vbObjectError + 4552, , _
        "The [[PHOTO]] token disappeared before the image was inserted."
End Sub

Private Sub FitInlinePicture( _
    ByVal picture As InlineShape, _
    ByVal maxWidth As Single, _
    ByVal maxHeight As Single)

    Dim widthScale As Double
    Dim heightScale As Double
    Dim scaleFactor As Double

    If picture.Width <= 0 Or picture.Height <= 0 Then
        Err.Raise vbObjectError + 4553, , _
            "Word inserted an image with invalid dimensions."
    End If

    widthScale = maxWidth / picture.Width
    heightScale = maxHeight / picture.Height
    scaleFactor = 1#
    If widthScale < scaleFactor Then scaleFactor = widthScale
    If heightScale < scaleFactor Then scaleFactor = heightScale
    If scaleFactor < 1# Then picture.Width = picture.Width * scaleFactor
End Sub

Private Function CountLiteralTokenInStories( _
    ByVal targetDoc As Document, _
    ByVal tokenText As String) As Long

    Dim firstStory As Range
    Dim currentStory As Range
    Dim searchRange As Range
    Dim tokenCount As Long
    Dim storyEnd As Long
    Dim nextStart As Long

    For Each firstStory In targetDoc.StoryRanges
        Set currentStory = firstStory
        Do While Not currentStory Is Nothing
            Set searchRange = currentStory.Duplicate
            storyEnd = currentStory.End

            Do
                With searchRange.Find
                    .ClearFormatting
                    .Replacement.ClearFormatting
                    .Text = tokenText
                    .Forward = True
                    .Wrap = wdFindStop
                    .Format = False
                    .MatchCase = True
                    .MatchWildcards = False
                    If Not .Execute Then Exit Do
                End With
                tokenCount = tokenCount + 1
                nextStart = searchRange.End
                If nextStart >= storyEnd Then Exit Do
                searchRange.SetRange Start:=nextStart, End:=storyEnd
            Loop
            Set currentStory = currentStory.NextStoryRange
        Loop
    Next firstStory

    CountLiteralTokenInStories = tokenCount
End Function

Private Function CountFieldsByType( _
    ByVal targetDoc As Document, _
    ByVal fieldType As Long) As Long

    Dim firstStory As Range
    Dim currentStory As Range
    Dim fieldItem As Field
    Dim fieldCount As Long

    For Each firstStory In targetDoc.StoryRanges
        Set currentStory = firstStory
        Do While Not currentStory Is Nothing
            For Each fieldItem In currentStory.Fields
                If fieldItem.Type = fieldType Then fieldCount = fieldCount + 1
            Next fieldItem
            Set currentStory = currentStory.NextStoryRange
        Loop
    Next firstStory

    CountFieldsByType = fieldCount
End Function

Private Sub UpdateFieldsInAllStories(ByVal targetDoc As Document)
    Dim firstStory As Range
    Dim currentStory As Range
    Dim fieldItem As Field

    For Each firstStory In targetDoc.StoryRanges
        Set currentStory = firstStory
        Do While Not currentStory Is Nothing
            For Each fieldItem In currentStory.Fields
                If Not fieldItem.Update Then
                    Err.Raise vbObjectError + 4560, , _
                        "Word could not update field type " & fieldItem.Type & "."
                End If
            Next fieldItem
            Set currentStory = currentStory.NextStoryRange
        Loop
    Next firstStory
End Sub

Private Sub ValidateCreatedFile( _
    ByVal filePath As String, _
    ByVal fileLabel As String)

    If Not FileExistsStrict(filePath) Then
        Err.Raise vbObjectError + 4570, , _
            "Word did not create the " & fileLabel & ": " & filePath
    End If
    If FileLen(filePath) <= 0 Then
        Err.Raise vbObjectError + 4571, , _
            "The " & fileLabel & " is empty: " & filePath
    End If
End Sub

Private Sub RequireTargetAbsent(ByVal filePath As String)
    If FileExistsStrict(filePath) Then
        Err.Raise vbObjectError + 4572, , _
            "Output already exists and will not be overwritten: " & filePath
    End If
End Sub

Private Function FileExistsStrict(ByVal filePath As String) As Boolean
    On Error GoTo FileCheckFailed
    FileExistsStrict = (Len(Dir$(filePath, FILE_ATTRIBUTES)) > 0)
    Exit Function

FileCheckFailed:
    Err.Raise vbObjectError + 4573, , _
        "The file path could not be checked: " & filePath & ". " & Err.Description
End Function

Private Sub RequireExistingFolder( _
    ByVal folderPath As String, _
    ByVal folderLabel As String)

    Dim attributes As Long

    On Error GoTo FolderCheckFailed
    attributes = GetAttr(folderPath)
    If (attributes And vbDirectory) = 0 Then
        Err.Raise vbObjectError + 4580, , _
            folderLabel & " is not a folder: " & folderPath
    End If
    Exit Sub

FolderCheckFailed:
    Err.Raise vbObjectError + 4581, , _
        folderLabel & " folder could not be accessed: " & folderPath & _
        ". " & Err.Description
End Sub

Private Sub EnsureOutputFolder(ByVal folderPath As String)
    Dim attributes As Long

    On Error GoTo CreateFolder
    attributes = GetAttr(folderPath)
    If (attributes And vbDirectory) = 0 Then
        Err.Raise vbObjectError + 4582, , _
            "Output path exists but is not a folder: " & folderPath
    End If
    Exit Sub

CreateFolder:
    If Err.Number <> 53 And Err.Number <> 76 Then
        Err.Raise vbObjectError + 4583, , _
            "Output folder could not be checked: " & folderPath & _
            ". " & Err.Description
    End If
    Err.Clear
    On Error GoTo CreateFailed
    MkDir folderPath
    Exit Sub

CreateFailed:
    Err.Raise vbObjectError + 4584, , _
        "Output folder could not be created: " & folderPath & _
        ". " & Err.Description
End Sub

Private Function CreateRunFolder(ByVal outputFolder As String) As String
    Dim candidate As String
    Dim attempt As Long

    Randomize
    For attempt = 1 To 50
        candidate = JoinPath(outputFolder, _
            "_run_" & Format$(Now, "yyyymmdd_hhnnss") & "_" & _
            Format$(Int(Rnd() * 1000000), "000000"))
        If Not FolderExists(candidate) Then
            MkDir candidate
            CreateRunFolder = candidate
            Exit Function
        End If
    Next attempt

    Err.Raise vbObjectError + 4585, , _
        "Could not create a unique run-specific staging folder."
End Function

Private Function FolderExists(ByVal folderPath As String) As Boolean
    Dim attributes As Long

    On Error GoTo NotFound
    attributes = GetAttr(folderPath)
    FolderExists = ((attributes And vbDirectory) <> 0)
    Exit Function

NotFound:
    If Err.Number = 53 Or Err.Number = 76 Then
        FolderExists = False
        Err.Clear
        Exit Function
    End If
    Err.Raise vbObjectError + 4586, , _
        "The folder path could not be checked: " & folderPath & _
        ". " & Err.Description
End Function

Private Sub RemoveEmptyRunFolder(ByVal runFolder As String)
    If Len(runFolder) = 0 Then Exit Sub
    If Len(Dir$(JoinPath(runFolder, "*"), FILE_ATTRIBUTES)) > 0 Then
        Err.Raise vbObjectError + 4587, , _
            "The staging folder is not empty after commit: " & runFolder
    End If
    RmDir runFolder
End Sub

Private Sub RestoreMailMergeState( _
    ByVal dataSource As MailMergeDataSource, _
    ByVal firstRecord As Long, _
    ByVal lastRecord As Long, _
    ByVal activeRecord As Long, _
    ByVal dataSourceReady As Boolean)

    If Not dataSourceReady Then Exit Sub
    dataSource.FirstRecord = firstRecord
    dataSource.LastRecord = lastRecord
    dataSource.ActiveRecord = activeRecord
End Sub

Private Function JoinPath( _
    ByVal folderPath As String, _
    ByVal childName As String) As String

    If Right$(folderPath, 1) = "\" Then
        JoinPath = folderPath & childName
    Else
        JoinPath = folderPath & "\" & childName
    End If
End Function

Private Function ContainsControlCharacter(ByVal valueText As String) As Boolean
    Dim index As Long
    Dim characterCode As Long

    For index = 1 To Len(valueText)
        characterCode = AscW(Mid$(valueText, index, 1))
        If characterCode >= 0 And characterCode <= 31 Then
            ContainsControlCharacter = True
            Exit Function
        End If
    Next index
End Function

Private Function IsReservedWindowsName(ByVal baseName As String) As Boolean
    Dim normalized As String
    Dim suffix As String

    normalized = UCase$(baseName)
    Select Case normalized
        Case "CON", "PRN", "AUX", "NUL", "CLOCK$"
            IsReservedWindowsName = True
            Exit Function
    End Select

    If Left$(normalized, 3) = "COM" Or Left$(normalized, 3) = "LPT" Then
        suffix = Mid$(normalized, 4)
        If suffix Like "[1-9]" Or suffix = ChrW$(&HB9) Or _
           suffix = ChrW$(&HB2) Or suffix = ChrW$(&HB3) Then
            IsReservedWindowsName = True
        End If
    End If
End Function

Microsoft documents that Field.Update returns whether an update succeeded, Field.Unlink replaces a field with its current result, and Document.ExportAsFixedFormat creates PDF or XPS output.

Know what the helper does not guarantee

No image-content authentication

The macro verifies the filename, path scope, extension, existence, and size. It does not decode the image or prove that the pictured subject is correct.

No source-status writeback

The Word macro does not change RecordStatus in Excel. Existing output blocks an ordinary repeat, but operators still need a controlled run log.

No atomic output pair

DOCX and PDF are moved separately. A failure between moves can leave one final file and one staged file.

No concurrency protection

Use one writer per output folder or add external coordination. Another process can change source or target state during a run.

No silent staging deletion

On failure, inspect the run-specific folder. The macro preserves evidence instead of recursively deleting partial files.

Word Desktop still required

Static code review cannot prove behavior for a specific Word build, data provider, security policy, font set, or template layout.

Run a six-record export pilot

Three obvious images

Use red, green, and blue images with their RecordID printed inside each file.

Mixed proportions

Include landscape, portrait, and square files to confirm aspect ratio and maximum-size behavior.

Long variable text

Force pagination changes around the image and confirm DOCX/PDF placement still matches.

Bad filename rejection

Use a disposable row with a path separator or unsupported extension and confirm preflight stops before merging.

Existing-output rejection

Create one conflicting target and confirm the run refuses to overwrite it.

Source-folder isolation

Copy completed outputs away from Photos and confirm every image remains visible in both formats.

Exit criteria

Approve only after every RecordID matches the intended image in DOCX and PDF, the output opens without the Photos folder, page layout is reviewed, and the exception tests stop safely.

Use the correct DocxForge Pro module if you leave Mail Merge

DocxForge Pro does not repair an existing INCLUDEPICTURE Mail Merge. It provides a different local Word-template generation workflow through Contractor and Factory.

Contractor: one case, several different documents

Review one case dataset and its assets, then generate several different documents for that case from different Word templates. Use it for a coordinated case pack.

Factory: many rows, one standard template

Select many independent Excel rows and apply one standard Word template to each selected row. Every row creates its own document for the same repeatable document type.

Migration boundary

Test your own data mapping, image slot, Word template, DOCX files, and PDFs. Moving away from Mail Merge changes the workflow; it is not an in-place repair of the old field.

Contractor: reviewed assets for one case

Keep one case’s reviewed data and image assets together, then choose its different documents.

DocxForge Pro Contractor Case Data screen with reviewed case values
Contractor Case Data: review one case and its shared assets.
DocxForge Pro Contractor Documents screen with different Word templates
Contractor Documents: select the different templates required for the case.

Factory: record-specific assets across many rows

Review independent Excel rows, then generate each row through one standard Word template.

DocxForge Pro Factory Excel Data screen with independent image records
Factory Excel Data: review row-specific values and image references.
DocxForge Pro Factory Documents screen with one standard Word template
Factory Documents: apply one tested template to the selected rows.
Use a local Word-template workflow when Mail Merge image fields remain fragileTry DocxForge Pro for 7 days free. Then $38 every 3 months • 14-day refund after purchase.
Contractor case packsFactory row batchesLocal processingDOCX + PDF
Start Free 7-Day Trial

Frequently asked questions

Why can an image look correct in Word but be wrong in the PDF?

The visible document may still contain a linked or cached field result. If the final merged document has not resolved and embedded the intended image before export, Word can export a stale, blank, or unavailable result.

Is this the same problem as every record showing the same image?

No. Repeated images usually begin with the source path, field construction, or record-by-record merge lifecycle. This article focuses on the later boundary: the generated Word result appears correct or nearly correct, but the exported PDF does not preserve the intended image.

Can I fix a small job by updating and unlinking the image field?

Sometimes. Update the field in the final merged document, verify the result, and unlink only that image field to preserve its current graphic. Do not blindly unlink every field. Test the exported PDF before release.

Why does the VBA example use a literal [[PHOTO]] token?

The macro keeps text fields in Mail Merge but avoids relying on an INCLUDEPICTURE field for the record image. After Word creates one merged record, the macro replaces exactly one literal token with the verified local file and embeds it before PDF export.

Does the macro overwrite existing DOCX or PDF files?

No in the ordinary single-writer workflow. It checks targets during preflight and again before committing staged files. The DOCX and PDF moves are separate operations, so concurrent writers still require coordination and a rare partial commit needs manual review.

Does DocxForge Pro repair an existing Mail Merge document?

No. It provides a separate local Word-template workflow. Contractor creates several different documents for one reviewed case from different templates. Factory applies one standard Word template to many independent Excel rows and creates a separate document per selected row.

Keep record-specific images embedded before final PDF exportRun DocxForge Pro locally. 7 days free, then $38 every 3 months • 14-day refund after purchase.
Verified image mappingEditable DOCXFinal PDFContractor + Factory
Start Free 7-Day Trial