Fix: Duplicate Output File Names in Batch Word and PDF Generation
When batch-generated Word or PDF files disappear, repeated filenames may be overwriting earlier output. The fix is to create a safe name for every record and check for existing DOCX and PDF files before saving.
Quick answer
If batch-generated documents keep overwriting each other, the fix is to stop saving with a shared name such as Report.docx or Invoice.pdf.
Build every output name from something unique and stable, such as a record ID, client reference, row number, timestamp, or a controlled suffix.
Then use that same base name for both the DOCX and PDF versions of the record.
The document is not disappearing by accident. The next file is being saved on top of it because the workflow keeps reusing the same name.
Why this matters in real document workflows
Duplicate names are not a cosmetic problem. They break traceability and can destroy output silently.
Earlier files get overwritten
One reused filename can wipe out a previously generated document without any visible drama during the run.
Audit trails get weaker
If filenames do not map cleanly to a record, later retrieval, review, and compliance checks become much harder.
Batch reruns become risky
A second run can overwrite the first run unless the naming logic is explicit about uniqueness and folder structure.
Manual cleanup wastes the gain
Renaming files after generation is exactly the kind of avoidable repair work that a stable workflow should remove.
What usually goes wrong
The naming failure is usually in the save step, not in the Word template.
Each Excel row creates its own Word document and matching PDF. The filenames identify the source record, so nothing is silently replaced.
It repeatedly saves as Report.docx, or it uses a new name for the Word file but the old name when exporting the PDF.
The solution is a single collision-safe filename rule, applied to both formats before either save operation.
What a reliable naming workflow looks like
Create the name once, verify that it is available, then use it for the DOCX/PDF pair.
Step 1: choose a record identifier
Use an invoice number, order ID, employee ID, or another field tied to the source row. Add the row number as a fallback when IDs repeat.
Step 2: sanitize the base name
Remove characters Windows does not allow in filenames, including slashes, colons, and question marks.
Step 3: check for collisions
If a DOCX or PDF with that name already exists, append _2, _3, and so on. A timestamp alone is not a reliable overwrite safeguard.
Step 4: save both formats together
Use exactly the same available base name for the Word document and its PDF so they can be matched later.
For a Data sheet with RecordID values INV-1042, INV-1042, and blank in rows 2–4:
INV-1042_0002.docx + INV-1042_0002.pdf
INV-1042_0003.docx + INV-1042_0003.pdf
Row_4_0004.docx + Row_4_0004.pdf
On a rerun in the same folder, the macro adds a numeric suffix rather than overwriting either existing file.
How to test the fix before a real batch
Test the macro on three rows before giving it a large workbook. Use the example Data sheet and the Output folder beside your Word template.
Test a duplicate record ID
Put INV-1042 in A2 and A3. Fill B and C with sample values. The first run should create different names ending in _0002 and _0003.
Test a blank record ID
Leave A4 blank but fill B4 or C4. The generated pair should use the fallback name Row_4_0004.docx and Row_4_0004.pdf.
Run the same workbook a second time
Do not delete the first outputs. A second run in the same folder should add _2 to each occupied base name instead of replacing the earlier DOCX/PDF files.
Check both files and their contents
Open a generated DOCX and PDF, confirm that the ClientName and Amount values match their Excel row, and check the pair count before using real records.
A grounded VBA helper
This Word VBA example reads Excel rows, cleans the record ID, appends the row number, checks for any existing DOCX or PDF, then adds a numeric suffix if needed. Each row produces a matching Word/PDF pair without intentionally overwriting an earlier run.
Before running: save the template as BatchTemplate.dotm, add ClientName and Amount bookmarks, and put BatchData.xlsx beside it. The workbook needs a sheet named Data with headers in row 1: A = RecordID, B = ClientName, C = Amount. In Word, enable macros for your trusted local template and run BatchGenerateUniqueDocs.
Option Explicit
' Put this macro in a Word macro-enabled template (.dotm).
' The folder must also contain BatchData.xlsx, sheet Data:
' A = RecordID, B = ClientName, C = Amount (headers in row 1).
' Add Word bookmarks named ClientName and Amount to the template.
Public Sub BatchGenerateUniqueDocs()
Dim xlApp As Object, xlWB As Object, xlSheet As Object
Dim doc As Document
Dim sourcePath As String, outputFolder As String
Dim lastRow As Long, rowNum As Long, created As Long
Dim recordID As String, stem As String, fileBase As String
Dim suffix As Long, failMessage As String
On Error GoTo Failed
If Len(ThisDocument.Path) = 0 Then
Err.Raise vbObjectError + 100, , "Save the .dotm template before running."
End If
sourcePath = ThisDocument.Path & "\BatchData.xlsx"
outputFolder = ThisDocument.Path & "\Output\"
If Len(Dir$(sourcePath)) = 0 Then
Err.Raise vbObjectError + 101, , "Missing Excel file: " & sourcePath
End If
' Check the folder path without the trailing backslash.
If Len(Dir$(Left$(outputFolder, Len(outputFolder) - 1), vbDirectory)) = 0 Then
MkDir Left$(outputFolder, Len(outputFolder) - 1)
End If
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
xlApp.DisplayAlerts = False
Set xlWB = xlApp.Workbooks.Open(sourcePath, 0, True)
Set xlSheet = xlWB.Worksheets("Data")
lastRow = xlSheet.Cells(xlSheet.Rows.Count, "A").End(-4162).Row
' If some RecordID cells are blank, find the last used data row in B/C.
If xlSheet.Cells(xlSheet.Rows.Count, "B").End(-4162).Row > lastRow Then _
lastRow = xlSheet.Cells(xlSheet.Rows.Count, "B").End(-4162).Row
If xlSheet.Cells(xlSheet.Rows.Count, "C").End(-4162).Row > lastRow Then _
lastRow = xlSheet.Cells(xlSheet.Rows.Count, "C").End(-4162).Row
For rowNum = 2 To lastRow
If Len(Trim$(CStr(xlSheet.Cells(rowNum, "A").Text))) > 0 Or _
Len(Trim$(CStr(xlSheet.Cells(rowNum, "B").Text))) > 0 Or _
Len(Trim$(CStr(xlSheet.Cells(rowNum, "C").Text))) > 0 Then
recordID = CleanFilePart(CStr(xlSheet.Cells(rowNum, "A").Text))
If Len(recordID) = 0 Then recordID = "Row_" & CStr(rowNum)
stem = Left$(recordID, 75) & "_" & Format$(rowNum, "0000")
fileBase = stem
suffix = 2
' Check BOTH extensions; never overwrite existing output on rerun.
Do While Len(Dir$(outputFolder & fileBase & ".docx")) > 0 Or _
Len(Dir$(outputFolder & fileBase & ".pdf")) > 0
fileBase = stem & "_" & CStr(suffix)
suffix = suffix + 1
Loop
Set doc = Documents.Add(Template:=ThisDocument.FullName, _
NewTemplate:=False)
If Not doc.Bookmarks.Exists("ClientName") Or _
Not doc.Bookmarks.Exists("Amount") Then
Err.Raise vbObjectError + 102, , _
"Template needs ClientName and Amount bookmarks."
End If
doc.Bookmarks("ClientName").Range.Text = _
CStr(xlSheet.Cells(rowNum, "B").Text)
doc.Bookmarks("Amount").Range.Text = _
CStr(xlSheet.Cells(rowNum, "C").Text)
doc.SaveAs2 FileName:=outputFolder & fileBase & ".docx", _
FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
doc.ExportAsFixedFormat _
OutputFileName:=outputFolder & fileBase & ".pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False
doc.Close SaveChanges:=False
Set doc = Nothing
created = created + 1
End If
Next rowNum
MsgBox "Generated " & created & " DOCX/PDF pairs in " & outputFolder, _
vbInformation
GoTo Cleanup
Failed:
failMessage = Err.Description
MsgBox "Batch stopped after " & created & " pairs: " & failMessage, _
vbExclamation
Cleanup:
On Error Resume Next
If Not doc Is Nothing Then doc.Close SaveChanges:=False
If Not xlWB Is Nothing Then xlWB.Close SaveChanges:=False
If Not xlApp Is Nothing Then xlApp.Quit
Set doc = Nothing
Set xlSheet = Nothing
Set xlWB = Nothing
Set xlApp = Nothing
On Error GoTo 0
End Sub
Private Function CleanFilePart(ByVal value As String) As String
Dim invalid As Variant, ch As Variant
Dim result As String
result = Trim$(value)
invalid = Array("\", "/", ":", "*", "?", Chr$(34), "<", ">", "|")
For Each ch In invalid
result = Replace$(result, CStr(ch), "_")
Next ch
result = Replace$(result, vbCr, "_")
result = Replace$(result, vbLf, "_")
result = Replace$(result, vbTab, "_")
Do While Len(result) > 0
If Right$(result, 1) <> "." And Right$(result, 1) <> " " Then Exit Do
result = Left$(result, Len(result) - 1)
Loop
CleanFilePart = result
End FunctionRun this macro from the Word template that contains your bookmarks. It keeps DOCX and PDF output aligned to the same unique record name and avoids silent overwrites during batch generation.
Where this VBA approach still has limits
The macro handles ordinary collisions in a single local run, but it is still a small example—not a complete batch-management system.
Excel display text can be misleading
The macro reads cells as they appear in Excel using .Text. If a column is too narrow and shows ####, widen it before running so the filename and inserted values are correct.
A failed PDF export can leave a DOCX
If Word saves the DOCX and the PDF export fails, the completed DOCX may remain without a matching PDF. Check and resolve partial output before rerunning.
Simultaneous jobs need separate output folders
Checking filenames is not the same as locking a file. Two users or processes saving at exactly the same time can still collide. Run this example sequentially or use separate folders.
Images and multiple templates need more code
This example fills two Word bookmarks. Photo handling, different template sets, richer file naming, and detailed per-row logs require additional implementation.
For additional filename patterns, read how to organize batch output names. For template data mapping, see how to fill Word templates from Excel.
Free VBA vs DocxForge Pro Factory: which fits your batch?
You do not need paid software just to repair one naming macro. Factory becomes more useful when generating Word/PDF files is recurring work and you want a configurable desktop workflow rather than maintaining VBA.
Use free VBA for a small, stable task
One Excel sheet, one Word template, two text bookmarks, occasional batches, and someone comfortable editing macros? The solution above may be enough.
Use Factory for repeated batch generation
Factory is designed for Excel-driven batches with file-naming rules, Word templates, optional PDF export, and local output management. It is included in the DocxForge Pro suite.
Handle more than two text fields
DocxForge Pro supports text tags and photo matching in template workflows, so you do not need to rewrite a bookmark macro whenever the document layout changes.
Know what the software still requires
It runs on Windows and requires Microsoft Word Desktop. Your Excel data and Word templates stay on your PC during generation; it does not replace Word.
If the macro already solves your problem, keep using it. If you spend time updating templates, matching photos, or repeating large batches, see the Factory workflow in DocxForge Pro before deciding.
Frequently asked questions
Short answers to the most common duplicate-filename questions.
Why do files disappear in a batch even though the run completes?
Because the save step can silently overwrite an earlier file when the same filename is reused later in the batch.
Is a timestamp enough by itself?
Sometimes, but the safer pattern is to combine a record identifier with a timestamp or row-based suffix so the name still maps clearly to the source record.
Should DOCX and PDF use the same base name?
Yes. That keeps the two outputs paired and makes later retrieval much easier.
What if the source ID is blank or duplicated?
Use a fallback such as the row number and add a uniqueness suffix. The workflow should never depend on a possibly empty filename field without a backup rule.
When is it time to standardize this more seriously?
Usually when batches are recurring, several people run the workflow, or overwritten files are causing rework, audit risk, or confusion about which output is final.