Fixes & Troubleshooting

Fix: Special Tags for Logo, Signature, or Stamp Not Inserting Images

Trace a missing business image through four points: the exact literal tag, its Word story range, the local source file, and the embedded inline image in the generated DOCX and PDF.

Exact literal tags
All Word stories
Embedded images
Diagnostic output
A visible image is not proof of authorization. Approve logo, signature, and stamp use separately from the technical insertion test.

Quick answer: test the tag, file, insertion, and saved result separately

Confirm the template contains exactly {{photo_logo}}, {{photo_signature}}, or {{photo_stamp}}; confirm the selected image file exists and is readable; replace the plain-text tag with an embedded InlineShape; then reopen or inspect both the DOCX and PDF result.

Do not diagnose from the PDF alone

If the DOCX already lacks the image, fix the tag or insertion path. If the DOCX is correct but the PDF is not, investigate the export step, layout, or renderer separately.

Match the symptom to the likely failure point

Literal tag remains visible

The replacement step never found the exact tag, searched the wrong Word story, or stopped before image insertion.

Tag disappears but no image appears

The range was deleted before insertion succeeded, the file was unreadable, or the insertion error was suppressed.

Image appears as a link or placeholder

The document retained an external link instead of an independent embedded copy.

Wrong image appears

The workflow resolved the wrong row, filename, folder, or case value even though Word successfully inserted an image.

Image appears in DOCX but not PDF

The insertion worked. Focus on PDF export, anchoring, pagination, clipping, or a renderer-specific issue.

Image is stretched or oversized

The workflow inserted the file but did not preserve its aspect ratio or enforce a tested maximum box.

Use one exact special-tag contract

Literal values

{{photo_logo}}; {{photo_signature}}; {{photo_stamp}}. Keep both brace pairs, the photo_ prefix, lowercase spelling, and underscores.

Plain Word text

For this diagnostic, each tag must appear once as plain text. It may sit in a normal table cell, but do not nest it in a field, content control, or existing image.

Controlled local files

Use a filename from the Images folder rather than a free-form absolute path. The example accepts PNG, JPG, and JPEG.

One occurrence per test

The diagnostic stops if a tag is missing or duplicated. That makes the test result unambiguous before you adapt the logic for intentional repeated images.

Run one isolated diagnostic before changing the production workflow

1. Copy the template into the test contract

Reference the template by filename from the Templates folder. The macro creates a new document instance and never saves back to the source file.

2. Use known-good images

Choose non-empty PNG or JPEG files with clear visual differences so a wrong mapping is obvious.

3. Inspect DOCX first

Confirm all three tags are gone, the correct images are present, proportions are preserved, and no image is linked.

4. Inspect PDF second

Compare size, position, clipping, page breaks, and visibility with the diagnostic DOCX.

Free VBA diagnostic: replace three literal tags in a test copy

Save the workbook as .xlsm. Create ImageTagTest with labels TemplateFile, LogoFile, SignatureFile, StampFile, and OutputName in A2:A6; enter the corresponding filenames in B2:B6.

All Word story ranges

Searches main text, headers, footers, and other available story chains instead of checking only Document.Content.

Exact occurrence count

Requires each case-sensitive tag once, then returns the actual found range for insertion.

Embedded and fitted

Uses InlineShapes.AddPicture with LinkToFile = False, preserves aspect ratio, and only scales oversized images down.

Separate diagnostic files

Stages one DOCX/PDF pair in a unique run folder and does not overwrite an existing diagnostic result.

Excel VBA — special image-tag diagnosticTest copy only
Option Explicit

Private Const SETUP_SHEET As String = "ImageTagTest"
Private Const TEMPLATE_FOLDER As String = "\Templates"
Private Const IMAGE_FOLDER As String = "\Images"
Private Const OUTPUT_FOLDER As String = "\ImageTagDiagnostics"
Private Const FILE_ATTRIBUTES As Long = 39

Private Const TAG_LOGO As String = "{{photo_logo}}"
Private Const TAG_SIGNATURE As String = "{{photo_signature}}"
Private Const TAG_STAMP As String = "{{photo_stamp}}"

Private Const WD_ALERTS_NONE As Long = 0
Private Const WD_DO_NOT_SAVE_CHANGES As Long = 0
Private Const WD_FORMAT_DOCX As Long = 16
Private Const WD_EXPORT_PDF As Long = 17
Private Const WD_FIND_STOP As Long = 0
Private Const WD_COLLAPSE_START As Long = 1
Private Const MSO_TRUE As Long = -1

Public Sub TestSpecialImageTags()
    Dim wb As Workbook
    Dim setupWs As Worksheet
    Dim templateFile As String
    Dim logoFile As String
    Dim signatureFile As String
    Dim stampFile As String
    Dim outputName As String
    Dim templatePath As String
    Dim logoPath As String
    Dim signaturePath As String
    Dim stampPath As String
    Dim outputPath As String
    Dim runFolder As String
    Dim stagedPaths As Collection
    Dim finalPaths As Collection
    Dim wdApp As Object
    Dim doc As Object
    Dim errorMessage As String

    On Error GoTo CleanFail

    Set wb = ThisWorkbook
    If Len(wb.Path) = 0 Then
        Err.Raise vbObjectError + 3800, , _
            "Save the diagnostic workbook as .xlsm before running the test."
    End If
    Set setupWs = RequireWorksheet(wb, SETUP_SHEET)
    ValidateSetupLabels setupWs

    templateFile = ReadRequiredText(setupWs.Range("B2"), "TemplateFile")
    logoFile = ReadRequiredText(setupWs.Range("B3"), "LogoFile")
    signatureFile = ReadRequiredText(setupWs.Range("B4"), "SignatureFile")
    stampFile = ReadRequiredText(setupWs.Range("B5"), "StampFile")
    outputName = ReadRequiredText(setupWs.Range("B6"), "OutputName")
    RequireStringValue setupWs.Range("B2"), "TemplateFile"
    RequireStringValue setupWs.Range("B3"), "LogoFile"
    RequireStringValue setupWs.Range("B4"), "SignatureFile"
    RequireStringValue setupWs.Range("B5"), "StampFile"
    RequireStringValue setupWs.Range("B6"), "OutputName"

    ValidateAssetFileName templateFile, Array("docx"), "TemplateFile"
    ValidateAssetFileName logoFile, Array("png", "jpg", "jpeg"), "LogoFile"
    ValidateAssetFileName signatureFile, _
        Array("png", "jpg", "jpeg"), "SignatureFile"
    ValidateAssetFileName stampFile, Array("png", "jpg", "jpeg"), _
        "StampFile"
    ValidateFileStem outputName, "OutputName"

    templatePath = wb.Path & TEMPLATE_FOLDER & "\" & templateFile
    logoPath = wb.Path & IMAGE_FOLDER & "\" & logoFile
    signaturePath = wb.Path & IMAGE_FOLDER & "\" & signatureFile
    stampPath = wb.Path & IMAGE_FOLDER & "\" & stampFile
    outputPath = wb.Path & OUTPUT_FOLDER

    RequireNonEmptyFile templatePath, "TemplateFile"
    RequireNonEmptyFile logoPath, "LogoFile"
    RequireNonEmptyFile signaturePath, "SignatureFile"
    RequireNonEmptyFile stampPath, "StampFile"
    ValidateOutputPair outputPath, outputName

    EnsureFolder outputPath
    runFolder = CreateRunFolder(outputPath)
    Set stagedPaths = New Collection
    Set finalPaths = New Collection

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

    Set doc = wdApp.Documents.Add(templatePath, False, 0, False)
    InsertSpecialImageTag doc, TAG_LOGO, logoPath, 180, 90
    InsertSpecialImageTag doc, TAG_SIGNATURE, signaturePath, 180, 90
    InsertSpecialImageTag doc, TAG_STAMP, stampPath, 120, 120
    StageDiagnosticDocument doc, runFolder, outputName, outputPath, _
        stagedPaths, finalPaths
    doc.Close WD_DO_NOT_SAVE_CHANGES
    Set doc = Nothing

    wdApp.NormalTemplate.Saved = True
    wdApp.Quit WD_DO_NOT_SAVE_CHANGES
    Set wdApp = Nothing

    CommitStagedFiles stagedPaths, finalPaths
    RemoveRunFolder runFolder

    MsgBox "Special image-tag test passed." & vbCrLf & _
        "Review the diagnostic DOCX and PDF: " & outputName, _
        vbInformation, "Special image-tag diagnostic"
    Exit Sub

CleanFail:
    errorMessage = Err.Description
    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 Len(runFolder) > 0 Then RemoveRunFolder runFolder
    On Error GoTo 0
    MsgBox "Diagnostic stopped: " & errorMessage & vbCrLf & _
        "The production template and production outputs were not changed.", _
        vbCritical, "Special image-tag diagnostic"
End Sub

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

Private Sub RequireStringValue(ByVal sourceCell As Range, _
                               ByVal fieldLabel As String)
    Dim rawValue As Variant
    rawValue = sourceCell.Value2
    If IsError(rawValue) Then Exit Sub
    If VarType(rawValue) <> vbString Then
        Err.Raise vbObjectError + 3816, , _
            fieldLabel & " must be stored as a text value."
    End If
End Sub

Private Sub ValidateSetupLabels(ByVal ws As Worksheet)
    Dim expected As Variant
    Dim rowNumber As Long
    expected = Array("TemplateFile", "LogoFile", "SignatureFile", _
        "StampFile", "OutputName")
    For rowNumber = 2 To 6
        If StrComp(CStr(ws.Cells(rowNumber, 1).Value2), _
                   CStr(expected(rowNumber - 2)), vbBinaryCompare) <> 0 Then
            Err.Raise vbObjectError + 3811, , _
                "ImageTagTest!A" & rowNumber & " must match exactly: " & _
                expected(rowNumber - 2)
        End If
    Next rowNumber
End Sub

Private Function ReadRequiredText(ByVal sourceCell As Range, _
                                  ByVal fieldLabel As String) As String
    Dim rawValue As Variant
    rawValue = sourceCell.Value2
    If IsError(rawValue) Then
        Err.Raise vbObjectError + 3812, , _
            fieldLabel & " contains an Excel error."
    End If
    ReadRequiredText = CStr(rawValue)
    If Len(ReadRequiredText) = 0 Then
        Err.Raise vbObjectError + 3813, , fieldLabel & " is required."
    End If
    If StrComp(ReadRequiredText, Trim$(ReadRequiredText), _
               vbBinaryCompare) <> 0 Then
        Err.Raise vbObjectError + 3814, , _
            fieldLabel & " has leading or trailing spaces."
    End If
    If ContainsControlCharacter(ReadRequiredText) Then
        Err.Raise vbObjectError + 3815, , _
            fieldLabel & " contains a control character."
    End If
End Function

Private Sub InsertSpecialImageTag(ByVal doc As Object, _
                                  ByVal tagText As String, _
                                  ByVal imagePath As String, _
                                  ByVal maximumWidth As Single, _
                                  ByVal maximumHeight As Single)
    Dim occurrenceCount As Long
    Dim tagRange As Object
    Dim picture As Object
    occurrenceCount = CountTagOccurrences(doc, tagText)
    If occurrenceCount = 0 Then
        Err.Raise vbObjectError + 3820, , _
            "Tag was not found in any Word story range: " & tagText
    End If
    If occurrenceCount > 1 Then
        Err.Raise vbObjectError + 3821, , _
            "Tag must appear exactly once for this diagnostic. Found " & _
            occurrenceCount & " occurrences: " & tagText
    End If
    Set tagRange = FindTagRange(doc, tagText)
    If tagRange Is Nothing Then
        Err.Raise vbObjectError + 3822, , _
            "Tag count succeeded, but the insertion range was not returned: " & _
            tagText
    End If
    If tagRange.Fields.Count > 0 Or _
       tagRange.ContentControls.Count > 0 Or _
       tagRange.InlineShapes.Count > 0 Then
        Err.Raise vbObjectError + 3823, , _
            "Tag must be plain text, not nested in a field, content control, " & _
            "or image: " & tagText
    End If
    tagRange.Text = vbNullString
    tagRange.Collapse WD_COLLAPSE_START
    Set picture = tagRange.InlineShapes.AddPicture( _
        imagePath, False, True, tagRange)
    picture.LockAspectRatio = MSO_TRUE
    FitImageDown picture, maximumWidth, maximumHeight
    picture.AlternativeText = tagText
    If picture.Range.InlineShapes.Count <> 1 Then
        Err.Raise vbObjectError + 3824, , _
            "Word did not return one embedded inline image for " & tagText
    End If
End Sub

Private Function CountTagOccurrences(ByVal doc As Object, _
                                     ByVal tagText As String) As Long
    Dim firstStory As Object
    Dim currentStory As Object
    Dim searchRange As Object
    Dim storyEnd As Long
    Dim nextStart As Long
    For Each firstStory In doc.StoryRanges
        Set currentStory = firstStory
        Do While Not currentStory Is Nothing
            storyEnd = currentStory.End
            Set searchRange = currentStory.Duplicate
            Do
                ConfigureTagFind searchRange, tagText
                If Not searchRange.Find.Execute Then Exit Do
                CountTagOccurrences = CountTagOccurrences + 1
                nextStart = searchRange.End
                If nextStart >= storyEnd Then Exit Do
                searchRange.SetRange nextStart, storyEnd
            Loop
            Set currentStory = currentStory.NextStoryRange
        Loop
    Next firstStory
End Function

Private Function FindTagRange(ByVal doc As Object, _
                              ByVal tagText As String) As Object
    Dim firstStory As Object
    Dim currentStory As Object
    Dim searchRange As Object
    For Each firstStory In doc.StoryRanges
        Set currentStory = firstStory
        Do While Not currentStory Is Nothing
            Set searchRange = currentStory.Duplicate
            ConfigureTagFind searchRange, tagText
            If searchRange.Find.Execute Then
                Set FindTagRange = searchRange.Duplicate
                Exit Function
            End If
            Set currentStory = currentStory.NextStoryRange
        Loop
    Next firstStory
End Function

Private Sub ConfigureTagFind(ByVal searchRange As Object, _
                             ByVal tagText As String)
    With searchRange.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = tagText
        .Forward = True
        .Wrap = WD_FIND_STOP
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
End Sub

Private Sub FitImageDown(ByVal picture As Object, _
                         ByVal maximumWidth As Single, _
                         ByVal maximumHeight As Single)
    If picture.Width > maximumWidth Then picture.Width = maximumWidth
    If picture.Height > maximumHeight Then picture.Height = maximumHeight
End Sub

Private Sub StageDiagnosticDocument(ByVal doc As Object, _
                                    ByVal runFolder As String, _
                                    ByVal outputName As String, _
                                    ByVal finalFolder As String, _
                                    ByVal stagedPaths As Collection, _
                                    ByVal finalPaths As Collection)
    Dim stagedDocx As String
    Dim stagedPdf As String
    Dim finalDocx As String
    Dim finalPdf As String
    stagedDocx = runFolder & "\diagnostic.docx"
    stagedPdf = runFolder & "\diagnostic.pdf"
    finalDocx = finalFolder & "\" & outputName & ".docx"
    finalPdf = finalFolder & "\" & outputName & ".pdf"
    doc.SaveAs2 stagedDocx, WD_FORMAT_DOCX
    doc.ExportAsFixedFormat stagedPdf, WD_EXPORT_PDF
    If Not FileExistsChecked(stagedDocx) Or _
       Not FileExistsChecked(stagedPdf) Then
        Err.Raise vbObjectError + 3830, , _
            "Word did not create both diagnostic files."
    End If
    stagedPaths.Add stagedDocx
    finalPaths.Add finalDocx
    stagedPaths.Add stagedPdf
    finalPaths.Add finalPdf
End Sub

Private Sub CommitStagedFiles(ByVal stagedPaths As Collection, _
                              ByVal finalPaths As Collection)
    Dim itemNumber As Long
    Dim sourcePath As String
    Dim destinationPath As String
    For itemNumber = 1 To finalPaths.Count
        If FileExistsChecked(CStr(finalPaths(itemNumber))) Then
            Err.Raise vbObjectError + 3831, , _
                "Final diagnostic file appeared during the run: " & _
                finalPaths(itemNumber)
        End If
        If Not FileExistsChecked(CStr(stagedPaths(itemNumber))) Then
            Err.Raise vbObjectError + 3832, , _
                "Staged diagnostic file is missing: " & _
                stagedPaths(itemNumber)
        End If
    Next itemNumber
    For itemNumber = 1 To finalPaths.Count
        sourcePath = CStr(stagedPaths(itemNumber))
        destinationPath = CStr(finalPaths(itemNumber))
        Name sourcePath As destinationPath
    Next itemNumber
End Sub

Private Sub ValidateOutputPair(ByVal outputPath As String, _
                               ByVal outputName As String)
    If FileExistsChecked(outputPath & "\" & outputName & ".docx") Or _
       FileExistsChecked(outputPath & "\" & outputName & ".pdf") Then
        Err.Raise vbObjectError + 3833, , _
            "Diagnostic output already exists: " & outputName
    End If
End Sub

Private Sub ValidateAssetFileName(ByVal fileName As String, _
                                  ByVal allowedExtensions As Variant, _
                                  ByVal fieldLabel As String)
    Dim forbidden As Variant
    Dim item As Variant
    Dim extension As String
    Dim dotPosition As Long
    Dim isAllowed As Boolean
    Dim baseName As String
    forbidden = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    For Each item In forbidden
        If InStr(1, fileName, CStr(item), vbBinaryCompare) > 0 Then
            Err.Raise vbObjectError + 3840, , _
                fieldLabel & " must be a filename, not a path."
        End If
    Next item
    If ContainsControlCharacter(fileName) Or _
       StrComp(fileName, Trim$(fileName), vbBinaryCompare) <> 0 Or _
       Right$(fileName, 1) = "." Or Right$(fileName, 1) = " " Then
        Err.Raise vbObjectError + 3841, , _
            fieldLabel & " contains unsafe characters."
    End If
    dotPosition = InStrRev(fileName, ".")
    If dotPosition > 1 And dotPosition < Len(fileName) Then
        extension = LCase$(Mid$(fileName, dotPosition + 1))
    End If
    For Each item In allowedExtensions
        If StrComp(extension, CStr(item), vbBinaryCompare) = 0 Then
            isAllowed = True
            Exit For
        End If
    Next item
    If Not isAllowed Then
        Err.Raise vbObjectError + 3842, , _
            fieldLabel & " has an unsupported extension: " & fileName
    End If
    baseName = Left$(fileName, dotPosition - 1)
    If InStr(1, baseName, ".", vbBinaryCompare) > 0 Then
        baseName = Left$(baseName, InStr(1, baseName, ".", _
            vbBinaryCompare) - 1)
    End If
    If IsReservedWindowsName(UCase$(baseName)) Then
        Err.Raise vbObjectError + 3843, , _
            fieldLabel & " starts with a reserved Windows device name."
    End If
End Sub

Private Sub ValidateFileStem(ByVal fileStem As String, _
                             ByVal fieldLabel As String)
    Dim forbidden As Variant
    Dim item As Variant
    Dim lowerStem As String
    Dim baseName As String
    If Len(fileStem) = 0 Or Len(fileStem) > 120 Then
        Err.Raise vbObjectError + 3844, , _
            fieldLabel & " must contain 1 to 120 characters."
    End If
    forbidden = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    For Each item In forbidden
        If InStr(1, fileStem, CStr(item), vbBinaryCompare) > 0 Then
            Err.Raise vbObjectError + 3845, , _
                fieldLabel & " contains a forbidden Windows character."
        End If
    Next item
    If ContainsControlCharacter(fileStem) Or _
       StrComp(fileStem, Trim$(fileStem), vbBinaryCompare) <> 0 Or _
       Right$(fileStem, 1) = "." Or Right$(fileStem, 1) = " " Then
        Err.Raise vbObjectError + 3846, , _
            fieldLabel & " contains unsafe characters."
    End If
    lowerStem = LCase$(fileStem)
    If Right$(lowerStem, 5) = ".docx" Or _
       Right$(lowerStem, 4) = ".pdf" Then
        Err.Raise vbObjectError + 3847, , _
            fieldLabel & " must be a filename stem without .docx or .pdf."
    End If
    baseName = fileStem
    If InStr(1, baseName, ".", vbBinaryCompare) > 0 Then
        baseName = Left$(baseName, InStr(1, baseName, ".", _
            vbBinaryCompare) - 1)
    End If
    If IsReservedWindowsName(UCase$(baseName)) Then
        Err.Raise vbObjectError + 3848, , _
            fieldLabel & " starts with a reserved Windows device name."
    End If
End Sub

Private Function IsReservedWindowsName(ByVal upperBase As String) As Boolean
    Dim finalCharacter As String
    Select Case upperBase
        Case "CON", "PRN", "AUX", "NUL", "CLOCK$"
            IsReservedWindowsName = True
            Exit Function
    End Select
    If Left$(upperBase, 3) = "COM" Or Left$(upperBase, 3) = "LPT" Then
        If Len(upperBase) = 4 And Mid$(upperBase, 4, 1) Like "[1-9]" Then
            IsReservedWindowsName = True
            Exit Function
        End If
        If Len(upperBase) = 4 Then
            finalCharacter = Mid$(upperBase, 4, 1)
            If finalCharacter = ChrW$(&HB9) Or _
               finalCharacter = ChrW$(&HB2) Or _
               finalCharacter = ChrW$(&HB3) Then
                IsReservedWindowsName = True
            End If
        End If
    End If
End Function

Private Function ContainsControlCharacter(ByVal textValue As String) As Boolean
    Dim position As Long
    Dim characterCode As Long
    For position = 1 To Len(textValue)
        characterCode = AscW(Mid$(textValue, position, 1))
        If characterCode >= 0 And characterCode < 32 Then
            ContainsControlCharacter = True
            Exit Function
        End If
    Next position
End Function

Private Sub RequireNonEmptyFile(ByVal filePath As String, _
                                ByVal fileLabel As String)
    If Not FileExistsChecked(filePath) Then
        Err.Raise vbObjectError + 3850, , _
            fileLabel & " was not found: " & filePath
    End If
    On Error GoTo SizeFailed
    If FileLen(filePath) <= 0 Then
        Err.Raise vbObjectError + 3851, , _
            fileLabel & " is empty: " & filePath
    End If
    Exit Sub
SizeFailed:
    If Err.Number = vbObjectError + 3851 Then
        Err.Raise Err.Number, , Err.Description
    End If
    Err.Raise vbObjectError + 3852, , _
        "Could not read " & fileLabel & " size: " & filePath & _
        ". " & Err.Description
End Sub

Private Function FileExistsChecked(ByVal filePath As String) As Boolean
    Dim foundName As String
    Dim attributes As Long
    On Error GoTo CheckFailed
    foundName = Dir$(filePath, FILE_ATTRIBUTES)
    If Len(foundName) = 0 Then
        FileExistsChecked = False
        Exit Function
    End If
    attributes = GetAttr(filePath)
    If (attributes And vbDirectory) = vbDirectory Then
        Err.Raise vbObjectError + 3853, , _
            "Expected a file but found a folder: " & filePath
    End If
    FileExistsChecked = True
    Exit Function
CheckFailed:
    Err.Raise vbObjectError + 3854, , _
        "Could not check file path: " & filePath & ". " & Err.Description
End Function

Private Sub EnsureFolder(ByVal folderPath As String)
    Dim attributes As Long
    If Len(Dir$(folderPath, vbDirectory)) = 0 Then
        MkDir folderPath
    Else
        attributes = GetAttr(folderPath)
        If (attributes And vbDirectory) <> vbDirectory Then
            Err.Raise vbObjectError + 3855, , _
                "Expected a folder but found a file: " & folderPath
        End If
    End If
End Sub

Private Function CreateRunFolder(ByVal outputPath As String) As String
    Dim attempt As Long
    Dim candidate As String
    For attempt = 0 To 99
        candidate = outputPath & "\_run_" & _
            Format$(Now, "yyyymmdd_hhnnss") & "_" & Format$(attempt, "00")
        If Len(Dir$(candidate, vbDirectory)) = 0 Then
            MkDir candidate
            CreateRunFolder = candidate
            Exit Function
        End If
    Next attempt
    Err.Raise vbObjectError + 3856, , _
        "Could not create a unique diagnostic run folder."
End Function

Private Sub RemoveRunFolder(ByVal runFolder As String)
    Dim itemName As String
    If Len(runFolder) = 0 Then Exit Sub
    itemName = Dir$(runFolder & "\*", FILE_ATTRIBUTES)
    Do While Len(itemName) > 0
        If itemName <> "." And itemName <> ".." Then
            If (GetAttr(runFolder & "\" & itemName) And vbDirectory) = 0 Then
                Kill runFolder & "\" & itemName
            End If
        End If
        itemName = Dir$()
    Loop
    RmDir runFolder
End Sub

Official Word VBA references: Document.StoryRanges, Find.Execute, and InlineShapes.AddPicture.

Understand the diagnostic limits

One occurrence by design

The example stops on duplicates. A production workflow may intentionally repeat a logo, but that requires a tested repeated-tag rule.

Extension is not format authentication

A .png or .jpg name and non-zero size do not prove valid image content. The Word insertion is the practical format test here.

StoryRanges are not every possible object

Grouped drawing objects and unusual embedded structures may require separate inspection.

Authorization remains separate

The macro cannot prove permission to apply a signature, stamp, or protected logo.

Check the image value in the correct DocxForge Pro workflow

DocxForge Pro has two different data shapes. Diagnose the tag and its image value in the module that owns the output.

Contractor

One case reuses shared data across several different documents created from different Word templates. Confirm the case image value and every template that contains the special tag.

Factory

Many independent Excel rows use one standard Word template. Confirm the image value on the affected row and the tag in that one template.

DocxForge Pro Contractor case data used for logo signature and stamp images
Contractor: verify the image value in shared case data.
DocxForge Pro Contractor documents using special image tags in different templates
Contractor: inspect each affected document template.
DocxForge Pro Factory Excel row containing an image value
Factory: verify the image value on the affected row.
DocxForge Pro Factory Word template using special image tags
Factory: inspect the one standard Word template.
Keep special images inside the tested local document workflowTry DocxForge Pro for 7 days free. Then $38 every 3 months • 14-day refund after purchase.
Contractor + FactoryExact special tagsLocal processingDOCX + PDF
Start Free 7-Day Trial

Frequently asked questions

Why is the logo, signature, or stamp still blank?

The usual causes are an altered literal tag, duplicate tag occurrences, a missing or unreadable image file, an unsupported filename contract, a tag nested inside another Word object, or a workflow that links instead of embedding the result.

Are the special tags case-sensitive?

Treat them as exact literal values: {{photo_logo}}, {{photo_signature}}, and {{photo_stamp}}. The diagnostic search is case-sensitive and does not use wildcards.

Does this VBA modify the production template?

No. It creates a new document from the configured template, replaces the three tags in that test instance, and writes a separate diagnostic DOCX and PDF. It does not save changes back to the source template.

Are the diagnostic images linked or embedded?

They are embedded with LinkToFile set to False and SaveWithDocument set to True. The diagnostic output should not depend on the source image remaining at the same path.

Does a successful insertion prove the image is authorized?

No. File presence and successful Word insertion do not prove permission to use a logo, signature, or stamp. Approval and signer authorization remain separate controls.

Do Contractor and Factory use the tags differently?

Contractor applies case data across several different documents and templates. Factory processes many independent rows through one standard template. In both workflows, verify the exact special tag and the image value supplied by that workflow.

Resolve the exact tag and image value before rerunning the batchRun DocxForge Pro locally. 7 days free, then $38 every 3 months • 14-day refund after purchase.
Exact tagsEmbedded imagesAspect ratioControlled output
Start Free 7-Day Trial