This VBA script automates the creation of individual files from a Word document using Mail Merge with data from an Excel file. Each row in the Excel file generates a separate file (PDF, DOCX, RTF, etc.), named based on a specified column.
- π Links a Word document to an Excel data source via Mail Merge.
- π Generates one file per row of data.
- ποΈ Names each file using a value from a chosen Excel column.
- π¨ Supports multiple output formats (PDF, DOCX, RTF, HTML, etc.).
- π₯οΈ Microsoft Word (2010 or later) with VBA support enabled.
- π An Excel file (
.xlsxor.xls) containing your data. - π A Word document (
.docx) with Mail Merge fields configured.
- π Create a Word document with Mail Merge fields (e.g.,
{Name},{Address}). Connect it to your Excel file using the Mailings tab. - π Ensure your Excel file has column headers matching the Mail Merge fields (e.g., "Name", "Address").
- Open your Word document.
- Press
Alt + F11to launch the VBA editor. - Go to Insert > Module and paste the code from
SaveAsInviduals.vba. - βοΈ Customize the script:
- Replace
"Name"with the column name for naming files (e.g.,"ID","CustomerName"). - Update
"C:\YourFolderPath\"to your desired output folder (e.g.,"C:\Users\YourName\Documents\Output\"). Ensure the folder exists. - Change the
fileFormatvariable to your desired format:wdFormatPDFfor.pdf(default).wdFormatDocumentDefaultfor.docx.wdFormatRTFfor.rtf.wdFormatHTMLfor.html.
- Replace
- Press
F5or go to Run > Run Sub/UserForm to execute. - π The script will generate one file per row in your Excel data!
dataField: Defines the Excel column used for naming output files.fileFormat: Sets the output format (e.g., PDF, DOCX). Modify this in the script to change formats.GetFileExtension: Helper function to match file extensions with formats.- π The script loops through each Mail Merge record, creates a new document, and saves it in the chosen format.
- π Keep your Excel and Word files open while running the script.
- π If column values are duplicated, files may overwrite each other. Modify the script to append a unique identifier (e.g., row number) if needed.
- πΎ Back up your files before running to avoid data loss.
- ποΈ Not all formats (e.g., HTML) may preserve formatting perfectlyβtest your output.
| Name | Address | Phone |
|---|---|---|
| John | 123 Main St | 555-1234 |
| Alice | 456 Oak Ave | 555-5678 |
C:\YourFolderPath\John.pdfC:\YourFolderPath\Alice.pdf