Mail Merge Image Fix

Fix: Word Mail Merge Showing the Same Image for Every Record

Diagnose repeated pictures, build the nested INCLUDEPICTURE field correctly, and generate each record with its verified, embedded image.

Record-specific paths
Verified photo insert
Images embedded
DOCX + PDF review
A correct preview is not proof of a correct batch. Test visibly different source images, inspect the generated DOCX files, and review the exported PDFs before release.

Quick answer: refresh the picture after Word knows the record

Text merge fields can change while an INCLUDEPICTURE result remains stale. First prove that every row supplies a different valid path. For automated output, merge one record at a time and replace the picture field with an image inserted directly from that record’s verified PhotoPath.

1. Verify the source path

Use three visibly different images and confirm that PhotoPath changes for all three records.

2. Check the nested field

The outer field must be INCLUDEPICTURE and the inner value must be a real MERGEFIELD.

3. Merge before updating

Update the image in the generated output, not only in the mail merge main document.

4. Embed before delivery

Insert the verified file with LinkToFile:=False and SaveWithDocument:=True so the recipient does not depend on your local path.

What the repeated image proves

If names and other text change but the picture does not, the data connection is working at least partly. The next checks are the actual path value, nested field construction, update timing, and whether the final file still contains an external link.

Find which layer is repeating the image

Do not start by changing every field switch. Match the visible symptom to the layer that can produce it.

All source rows contain one path

Cause: an Excel formula, copied value, or lookup returns the same file. Fix: inspect the evaluated PhotoPath values, not only the formula pattern.

The path changes, but Preview does not

Cause: Word is showing a saved field result. Fix: update the field and judge the generated output, not Preview Results alone.

Typed braces appear as text

Cause: ordinary { } characters are not Word field delimiters. Fix: create both field pairs with Ctrl+F9.

DOCX is right, PDF is wrong

Cause: export happened before the image field finished updating or while it still referenced a stale result. Fix: update, embed, save, then export.

The file works only on one PC

Cause: the final document still links to a local or network path. Fix: unlink the refreshed picture field to keep its current graphic in the document.

Header or text-box image stays stale

Cause: updating Document.Fields reaches the main story only. Fix: update the relevant Word story ranges as the helper below does.

Build the nested INCLUDEPICTURE field correctly

Connect the Word main document to the Excel data source first. Microsoft explains how column headings become merge fields in its mail merge field guide.

Required field structure
{ INCLUDEPICTURE "{ MERGEFIELD PhotoPath }" \* MERGEFORMAT }

Create the outer braces with Ctrl+F9, place the cursor inside them, and create the inner braces with Ctrl+F9 again. Do not type or paste ordinary braces. Use Alt+F9 to switch between field codes and results, and F9 to update a selected field. These shortcuts are listed in Microsoft’s Word keyboard reference.

Use the full path value

PhotoPath should resolve to the exact local image for that row, for example C:\ApprovedMailMergePhotos\employee-0042.png.

Keep the image inline

Place the field in a controlled paragraph or table cell. Inline results are easier to update and keep with surrounding text than floating shapes.

Do not add \d casually

The \d switch keeps picture data outside the document. The helper updates and unlinks the field so the final graphic is embedded instead.

The field code is necessary but not sufficient. A correct field can still show a saved result until Word updates it in the generated record.

Use a data source that makes mistakes visible

Save the Word main document as a macro-enabled .docm file. Connect it to an Excel sheet with the exact column names below, and set the VBA constant APPROVED_PHOTO_ROOT to the trusted local folder that contains the images.

Required Excel columns

A — DocumentID; B — PhotoPath; C — Status. Store DocumentID as text when leading zeros matter. Use READY only for records approved for this run.

DocumentID

Use a stable unique identifier. The helper cleans it for the output name and rejects duplicates created by cleaning.

PhotoPath

Use a full path to a nonempty PNG, JPG, or JPEG inside the approved root. The helper rejects files outside that root.

Status

Only READY records run. Draft and rejected rows remain outside the batch.

The approved-root check is a useful control for a trusted local folder. It is not a complete defense against reparse points, symbolic links, or an untrusted filesystem.
If Word reports an unknown record count (-1), the macro stops rather than guessing the batch range. Reconnect the Excel source and confirm that Word can enumerate the records before retrying.

Fix a small merge manually before automating it

Use three records with unmistakably different images. This separates a bad path from a stale Word result before VBA adds another layer.

1. Preview three records

Confirm that the text fields and PhotoPath values change. Preview alone does not approve the image result.

2. Merge to a new document

Choose Finish & Merge → Edit Individual Documents. Select the picture field in the output and press F9.

3. Embed only the picture field

After confirming the correct image, select that picture field and press Ctrl+Shift+F9. Do not unlink every field in the document blindly.

Stop condition

If the three generated records still show one image after an explicit field update, return to the field construction and source paths. Automation should not hide an unresolved manual test.

Free Word VBA helper: merge, verify, and embed one record at a time

This macro runs from the saved Word mail merge main document. It preflights every READY record, confirms that Word includes the record and creates a new document, finds each INCLUDEPICTURE placement across Word story ranges, and inserts the verified PhotoPath directly as an embedded image before saving separate DOCX/PDF files.

Before running it

Save the main document as .docm, attach the Excel source, create the nested field shown above, change APPROVED_PHOTO_ROOT, and test on disposable copies. The code creates one output pair per READY record; it does not create one combined multi-record document.

Option Explicit

Private Const OUTPUT_FOLDER_NAME As String = "GeneratedMailMergeImages"
Private Const READY_STATUS As String = "READY"
Private Const APPROVED_PHOTO_ROOT As String = "C:\ApprovedMailMergePhotos"
Private Const FILE_ATTRIBUTES As Long = 7
Private Const FOLDER_ATTRIBUTES As Long = 22

Public Sub MergeImageRecordsSafely()
    Dim mainDoc As Document
    Dim mergedDoc As Document
    Dim dataSource As MailMergeDataSource
    Dim nameKeys As Object
    Dim photoRoot As String
    Dim outputFolder As String
    Dim runFolder As String
    Dim documentId As String
    Dim photoPath As String
    Dim statusText As String
    Dim safeId As String
    Dim baseName As String
    Dim tempDocxPath As String
    Dim tempPdfPath As String
    Dim finalDocxPath As String
    Dim finalPdfPath As String
    Dim recordNumber As Long
    Dim recordCount As Long
    Dim readyCount As Long
    Dim generatedCount As Long
    Dim pictureCount As Long
    Dim documentCountBefore As Long
    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 mail merge main document"
    If Len(mainDoc.Path) = 0 Then
        Err.Raise vbObjectError + 3000, , _
            "Save the Word mail merge main document before running the macro."
    End If

    If mainDoc.MailMerge.State <> wdMainAndDataSource Then
        Err.Raise vbObjectError + 3001, , _
            "Connect the Word main document to the Excel data source first."
    End If

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

    currentStep = "checking the required data fields"
    RequireDataField dataSource, "DocumentID"
    RequireDataField dataSource, "PhotoPath"
    RequireDataField dataSource, "Status"

    recordCount = dataSource.RecordCount
    If recordCount = -1 Then
        Err.Raise vbObjectError + 3002, , _
            "Word could not determine the data-source record count. " & _
            "Reconnect the Excel source and confirm that Word can enumerate it."
    End If
    If recordCount < 1 Then
        Err.Raise vbObjectError + 3002, , _
            "No records were found in the connected data source."
    End If

    currentStep = "checking the approved photo folder"
    photoRoot = NormalizeExistingFolder(APPROVED_PHOTO_ROOT)

    outputFolder = JoinPath(mainDoc.Path, OUTPUT_FOLDER_NAME)
    EnsureFolderExists outputFolder

    currentStep = "preflighting READY records"
    Set nameKeys = CreateObject("Scripting.Dictionary")
    nameKeys.CompareMode = vbTextCompare

    For recordNumber = 1 To recordCount
        dataSource.ActiveRecord = recordNumber
        statusText = ReadDataField(dataSource, "Status")

        If StrComp(statusText, READY_STATUS, vbTextCompare) = 0 Then
            If Not dataSource.Included Then
                Err.Raise vbObjectError + 3021, , _
                    "READY record " & recordNumber & _
                    " is excluded in Mail Merge Recipients."
            End If

            readyCount = readyCount + 1
            documentId = ReadRequiredDataField( _
                dataSource, "DocumentID", recordNumber)
            photoPath = ReadRequiredDataField( _
                dataSource, "PhotoPath", recordNumber)

            photoPath = ValidateApprovedPhoto( _
                photoPath, photoRoot, recordNumber)

            safeId = CleanFileName(documentId)
            If Len(safeId) = 0 Then
                Err.Raise vbObjectError + 3003, , _
                    "DocumentID becomes empty after file-name cleaning at record " & _
                    recordNumber & "."
            End If

            baseName = "MailMerge_" & safeId
            If nameKeys.Exists(baseName) Then
                Err.Raise vbObjectError + 3004, , _
                    "Duplicate output name after cleaning: " & baseName & _
                    " (record " & recordNumber & ")."
            End If
            nameKeys.Add baseName, recordNumber

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

            If FileExists(finalDocxPath) Or FileExists(finalPdfPath) Then
                Err.Raise vbObjectError + 3005, , _
                    "Output already exists for record " & recordNumber & _
                    ": " & baseName
            End If
        End If
    Next recordNumber

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

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

    For recordNumber = 1 To recordCount
        dataSource.ActiveRecord = recordNumber
        statusText = ReadDataField(dataSource, "Status")

        If StrComp(statusText, READY_STATUS, vbTextCompare) = 0 Then
            If Not dataSource.Included Then
                Err.Raise vbObjectError + 3021, , _
                    "READY record " & recordNumber & _
                    " became excluded before generation."
            End If

            documentId = ReadRequiredDataField( _
                dataSource, "DocumentID", recordNumber)
            photoPath = ReadRequiredDataField( _
                dataSource, "PhotoPath", recordNumber)
            photoPath = ValidateApprovedPhoto( _
                photoPath, photoRoot, recordNumber)

            safeId = CleanFileName(documentId)
            baseName = "MailMerge_" & safeId
            tempDocxPath = JoinPath(runFolder, baseName & ".docx")
            tempPdfPath = JoinPath(runFolder, baseName & ".pdf")
            finalDocxPath = JoinPath(outputFolder, baseName & ".docx")
            finalPdfPath = JoinPath(outputFolder, baseName & ".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 Then
                Err.Raise vbObjectError + 3022, , _
                    "Mail Merge did not create a new document for record " & _
                    recordNumber & "."
            End If

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

            currentStep = "inserting the verified image for record " & _
                recordNumber
            pictureCount = ReplaceIncludePictureFieldsWithVerifiedPhoto( _
                mergedDoc, photoPath)
            If pictureCount = 0 Then
                Err.Raise vbObjectError + 3007, , _
                    "No INCLUDEPICTURE placement was found in the merged output for " & _
                    "record " & recordNumber & "."
            End If

            currentStep = "saving 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

            If Not FileExists(tempDocxPath) Or Not FileExists(tempPdfPath) Then
                Err.Raise vbObjectError + 3008, , _
                    "Word did not create both temporary files for record " & _
                    recordNumber & "."
            End If

            currentStep = "committing final files for record " & recordNumber
            If FileExists(finalDocxPath) Or FileExists(finalPdfPath) Then
                Err.Raise vbObjectError + 3009, , _
                    "A final output appeared during the run: " & baseName
            End If

            Name tempDocxPath As finalDocxPath
            Name tempPdfPath As finalPdfPath
            generatedCount = generatedCount + 1
        End If
    Next recordNumber

    CleanupRunFolder runFolder
    runFolder = vbNullString

    If dataSourceReady Then
        dataSource.FirstRecord = oldFirstRecord
        dataSource.LastRecord = oldLastRecord
        dataSource.ActiveRecord = oldActiveRecord
    End If

    Application.DisplayAlerts = oldDisplayAlerts
    Application.ScreenUpdating = oldScreenUpdating

    MsgBox generatedCount & _
        " record(s) generated with refreshed, embedded images.", _
        vbInformation, "Mail merge 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
    If Len(runFolder) > 0 Then
        CleanupRunFolder runFolder
    End If
    If dataSourceReady Then
        dataSource.FirstRecord = oldFirstRecord
        dataSource.LastRecord = oldLastRecord
        dataSource.ActiveRecord = oldActiveRecord
    End If
    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 moved to the final folder were not deleted. " & _
        "Review them before retrying.", _
        vbCritical, "Mail merge 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 + 3010, , _
        "Required data field not found: " & fieldName
End Sub

Private Function ReadDataField( _
    ByVal dataSource As MailMergeDataSource, _
    ByVal fieldName As String) As String

    ReadDataField = Trim$(CStr(dataSource.DataFields(fieldName).Value))
End Function

Private Function ReadRequiredDataField( _
    ByVal dataSource As MailMergeDataSource, _
    ByVal fieldName As String, _
    ByVal recordNumber As Long) As String

    Dim valueText As String

    valueText = ReadDataField(dataSource, fieldName)
    If Len(valueText) = 0 Then
        Err.Raise vbObjectError + 3011, , _
            fieldName & " is blank at record " & recordNumber & "."
    End If

    ReadRequiredDataField = valueText
End Function

Private Function ValidateApprovedPhoto( _
    ByVal sourcePath As String, _
    ByVal approvedRoot As String, _
    ByVal recordNumber As Long) As String

    Dim fso As Object
    Dim fullPath As String
    Dim extensionText As String

    Set fso = CreateObject("Scripting.FileSystemObject")
    fullPath = fso.GetAbsolutePathName(sourcePath)

    If Not IsPathUnderRoot(fullPath, approvedRoot) Then
        Err.Raise vbObjectError + 3012, , _
            "PhotoPath is outside the approved folder at record " & _
            recordNumber & ": " & sourcePath
    End If

    If Not FileExists(fullPath) Then
        Err.Raise vbObjectError + 3013, , _
            "Photo file not found at record " & recordNumber & _
            ": " & fullPath
    End If

    If FileLen(fullPath) <= 0 Then
        Err.Raise vbObjectError + 3014, , _
            "Photo file is empty at record " & recordNumber & _
            ": " & fullPath
    End If

    extensionText = LCase$(fso.GetExtensionName(fullPath))
    Select Case extensionText
        Case "png", "jpg", "jpeg"
        Case Else
            Err.Raise vbObjectError + 3015, , _
                "PhotoPath must use PNG, JPG, or JPEG at record " & _
                recordNumber & "."
    End Select

    ValidateApprovedPhoto = fullPath
End Function

Private Function NormalizeExistingFolder( _
    ByVal folderPath As String) As String

    Dim fso As Object
    Dim fullPath As String

    If Len(Trim$(folderPath)) = 0 Then
        Err.Raise vbObjectError + 3016, , _
            "APPROVED_PHOTO_ROOT is blank."
    End If

    If Len(Dir$(folderPath, FOLDER_ATTRIBUTES)) = 0 Then
        Err.Raise vbObjectError + 3017, , _
            "Approved photo folder not found: " & folderPath
    End If

    Set fso = CreateObject("Scripting.FileSystemObject")
    fullPath = fso.GetAbsolutePathName(folderPath)
    NormalizeExistingFolder = RemoveTrailingSeparator(fullPath)
End Function

Private Function IsPathUnderRoot( _
    ByVal sourcePath As String, _
    ByVal approvedRoot As String) As Boolean

    Dim normalizedSource As String
    Dim normalizedRoot As String

    normalizedSource = LCase$(Replace(sourcePath, "/", "\"))
    normalizedRoot = LCase$(Replace(approvedRoot, "/", "\"))
    normalizedRoot = RemoveTrailingSeparator(normalizedRoot) & "\"

    IsPathUnderRoot = _
        (Left$(normalizedSource, Len(normalizedRoot)) = normalizedRoot)
End Function

Private Function ReplaceIncludePictureFieldsWithVerifiedPhoto( _
    ByVal targetDoc As Document, _
    ByVal verifiedPhotoPath As String) As Long

    Dim firstStory As Range
    Dim currentStory As Range
    Dim targetRange As Range
    Dim fieldItem As Field
    Dim picture As InlineShape
    Dim fieldIndex As Long
    Dim insertedCount As Long
    Dim maxWidth As Single
    Dim maxHeight As Single
    Dim hasSizeBox As Boolean

    For Each firstStory In targetDoc.StoryRanges
        Set currentStory = firstStory

        Do While Not currentStory Is Nothing
            For fieldIndex = currentStory.Fields.Count To 1 Step -1
                Set fieldItem = currentStory.Fields(fieldIndex)

                If fieldItem.Type = wdFieldIncludePicture Then
                    hasSizeBox = False
                    If fieldItem.Result.InlineShapes.Count > 0 Then
                        maxWidth = fieldItem.Result.InlineShapes(1).Width
                        maxHeight = fieldItem.Result.InlineShapes(1).Height
                        hasSizeBox = (maxWidth > 0 And maxHeight > 0)
                    End If

                    Set targetRange = fieldItem.Result.Duplicate
                    fieldItem.Delete
                    targetRange.Collapse Direction:=wdCollapseStart

                    Set picture = targetRange.InlineShapes.AddPicture( _
                        FileName:=verifiedPhotoPath, _
                        LinkToFile:=False, _
                        SaveWithDocument:=True, _
                        Range:=targetRange)

                    picture.LockAspectRatio = msoTrue
                    If hasSizeBox Then
                        FitInlinePictureToBox picture, maxWidth, maxHeight
                    End If

                    If picture.Range.InlineShapes.Count = 0 Then
                        Err.Raise vbObjectError + 3019, , _
                            "Word did not retain the explicitly inserted image."
                    End If

                    insertedCount = insertedCount + 1
                End If
            Next fieldIndex

            Set currentStory = currentStory.NextStoryRange
        Loop
    Next firstStory

    ReplaceIncludePictureFieldsWithVerifiedPhoto = insertedCount
End Function

Private Sub FitInlinePictureToBox( _
    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 Exit Sub
    If maxWidth <= 0 Or maxHeight <= 0 Then Exit Sub

    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 If
End Sub

Private Sub EnsureFolderExists(ByVal folderPath As String)
    If Len(Dir$(folderPath, FOLDER_ATTRIBUTES)) = 0 Then
        MkDir folderPath
    End If
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 Len(Dir$(candidate, FOLDER_ATTRIBUTES)) = 0 Then
            MkDir candidate
            CreateRunFolder = candidate
            Exit Function
        End If
    Next attempt

    Err.Raise vbObjectError + 3020, , _
        "Could not create a unique temporary run folder."
End Function

Private Sub CleanupRunFolder(ByVal runFolder As String)
    Dim fso As Object

    If Len(runFolder) = 0 Then Exit Sub

    Set fso = CreateObject("Scripting.FileSystemObject")
    If fso.FolderExists(runFolder) Then
        fso.DeleteFolder runFolder, True
    End If
End Sub

Private Function FileExists(ByVal filePath As String) As Boolean
    FileExists = (Len(Dir$(filePath, FILE_ATTRIBUTES)) > 0)
End Function

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 RemoveTrailingSeparator( _
    ByVal folderPath As String) As String

    Do While Len(folderPath) > 3 And _
        (Right$(folderPath, 1) = "\" Or Right$(folderPath, 1) = "/")
        folderPath = Left$(folderPath, Len(folderPath) - 1)
    Loop

    RemoveTrailingSeparator = folderPath
End Function

Private Function CleanFileName(ByVal valueText As String) As String
    Dim invalidCharacters As Variant
    Dim characterItem As Variant
    Dim characterCode As Long

    valueText = Trim$(valueText)
    invalidCharacters = Array("\", "/", ":", "*", "?", Chr$(34), "<", ">", "|")

    For Each characterItem In invalidCharacters
        valueText = Replace(valueText, CStr(characterItem), "_")
    Next characterItem

    For characterCode = 0 To 31
        valueText = Replace(valueText, Chr$(characterCode), "_")
    Next characterCode

    Do While Len(valueText) > 0 And _
        (Right$(valueText, 1) = "." Or Right$(valueText, 1) = " ")
        valueText = Left$(valueText, Len(valueText) - 1)
    Loop

    If Len(valueText) > 80 Then valueText = Left$(valueText, 80)
    CleanFileName = valueText
End Function

The helper uses Word’s documented record boundaries through FirstRecord, checks participation through DataSource.Included, stops when RecordCount is unknown, inserts the verified file with InlineShapes.AddPicture, and creates PDF output with ExportAsFixedFormat.

Preflight before merging

Required fields, READY records, image existence, file type, approved root, duplicate names, and existing outputs are checked first.

One record per merge

The macro sets the same record as FirstRecord, LastRecord, and ActiveRecord before executing the merge.

All Word stories checked

The update loop covers the main story and linked story ranges such as headers, footers, and text frames.

Verified path inserted directly

Other fields remain untouched. Each INCLUDEPICTURE placement is replaced with the file passed from the current record’s checked PhotoPath.

Temporary output first

DOCX and PDF are created inside a unique run folder and moved only after both files exist.

No ordinary overwrite

Final names are checked twice, and the final move fails if another file appears during the run.

Desktop test still required

Static review cannot confirm a particular Word build, data provider, header layout, security policy, or PDF rendering. Run the six-record pilot below in Word Desktop before using production data.

Use the DocxForge Pro workflow that matches the output

A template-based generator avoids depending on Word Mail Merge’s cached picture result. The correct module still depends on whether the job is many rows through one template or one case across several different templates.

Factory: many Excel rows

Use one standard Word template and create a separate document for each selected row.

Factory image fit

Use it for employee cards, certificates, product sheets, or other repeated layouts with a different image per row.

Contractor: one case

Keep one case’s data and assets together and create several different documents from different Word templates.

Contractor image fit

Use it when one case photo, logo, signature, or stamp must appear across a set of different case documents.

Product boundary

DocxForge Pro does not repair the INCLUDEPICTURE field inside an existing Mail Merge. It provides a different local generation workflow. Test your own template, image mapping, DOCX files, and PDFs before migration.

Compare the two local generation workflows

The screenshots are grouped by module so a many-row batch is not confused with a one-case document pack.

Factory: many rows, one standard template

DocxForge Pro Factory Excel data screen
Review row-specific data and image references before generation.
DocxForge Pro Factory documents screen
Create one standardized output for each selected row.

Contractor: one case, several different documents

DocxForge Pro Contractor case data screen
Keep the reviewed data and image assets for one case together.
DocxForge Pro Contractor documents screen
Reuse them across different case documents and templates.
DocxForge Pro pricing

7 days free, then $38 every 3 months • 14-day refund after purchase • Microsoft Word Desktop required • local processing.

Run a six-record repeated-image pilot

Use outputs that make a wrong image impossible to miss before you trust a larger batch.

Red test image

Use a wide red image with the record ID printed inside it.

Green test image

Use a tall green image with a different record ID.

Blue test image

Use a square blue image so both identity and proportions are obvious.

Header placement

Place one test field in a header and confirm the story-range update reaches it.

Missing-file rejection

Use one bad path in a disposable source and confirm preflight stops before merging.

Existing-output rejection

Create one conflicting file and confirm the macro stops without replacing it.

Pilot exit criteria

Approve only after every DocumentID matches the intended image in both DOCX and PDF, the files open without access to the source image folder, and a reviewer confirms the layout at normal zoom and print size.

Frequently asked questions

Why does Word Mail Merge show the first image for every record?

The usual causes are a repeated source path, an incorrectly constructed nested field, or an INCLUDEPICTURE result that was not refreshed after the record was merged. Check those layers in that order.

Can I type the braces around INCLUDEPICTURE and MERGEFIELD?

No. Word fields require real field delimiters. Create the outer and inner brace pairs with Ctrl+F9, use Alt+F9 to inspect the code, and use F9 to update the selected field.

Should I add the \d switch to INCLUDEPICTURE?

Not for the final embedded-output workflow shown here. The \d switch keeps picture data outside the document. The helper replaces the picture field with an image inserted explicitly using LinkToFile:=False and SaveWithDocument:=True.

Does the VBA helper handle images in headers and text boxes?

It walks Word story ranges rather than only Document.Fields, so it is designed to reach main text, headers, footers, and linked text-frame stories. It then replaces each discovered picture field with the verified file. Test the actual template because complex shapes, protected regions, and unusual layouts can still behave differently.

Can the macro overwrite an existing DOCX or PDF?

It checks final names before and after generation, creates both files in a unique temporary folder, and uses a final move that fails when a destination already exists. The DOCX/PDF pair cannot be committed atomically, so shared output folders still require coordination and review after a rare partial commit.

Which DocxForge Pro module fits record-specific images?

Factory fits many Excel rows processed through one standard Word template. Contractor fits one case that produces several different documents from different templates. Choose by the document workflow, not by the image type alone.

Generate the right image for every record

Prove the paths, refresh after each record is merged, embed the result, and review both DOCX and PDF. When Mail Merge remains too fragile, move the workflow to the DocxForge Pro module that matches the job.

7 days free, then $38 every 3 months • 14-day refund after purchase • Microsoft Word Desktop required • local processing.