Mail Merge Image Word and Grouping

NellyAblon Posted messages 10 Status Membre -  
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   -

Hello,

I have two issues with Word mail merge in a 3x5 label format that represents a small directory with information for each person:

1) I used an INCLUDEPICTURE field to insert an image via a URL link contained in my Excel file, and when I have blank labels it says "Error! Filename not specified." Is there a way to not display it? I tried using an IF field, but then my image does not work.

2) I would like to group the labels by department with the department name displayed at the top of each page and a page break when changing departments. So far, other than creating a separate mail merge for each department, I haven't succeeded.

Thank you for your help.


13 réponses

Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 

Hello,

The INCLUDEPICTURE field can cause a problem when it tries to load an image with an empty or incorrect URL, resulting in the error "Error! File name not specified". It is possible to use a conditional IF field to avoid displaying this error, but this requires some adjustments to not disrupt the image insertion.

Modify the structure of the IF field: Use an IF field that checks whether the link to the image is empty or not. If the field is empty, nothing displays; otherwise, the image is inserted.

The structure of the field will look like this:

{ IF { MERGEFIELD "ImageLink" } = "" "" "{ INCLUDEPICTURE { MERGEFIELD "ImageLink" } \d }" }

Use the Alt + F9 key combination to toggle to "field code" mode in Word to manually insert these fields, as the brackets { } cannot be typed directly. They must be inserted with Ctrl + F9.

Once the mail merge is complete, you may need to select the entire document (Ctrl + A) and press F9 to update all fields and force the images to display.


0
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 

{ MERGEFIELD "LienImage" } : This is the field where the image link is stored in Excel.

0
NellyAblon Posted messages 10 Status Membre
 

Thank you Bruno

But no, actually I already tried and it doesn't work. When I use an IF field as indicated, the image no longer updates in the merged document when pressing F9.

0
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 

Okay. But there may be an alternative by adding an empty image to the database.


If using macros is not practical for you, another solution is to add a link to an empty image directly in your data source (the Excel file). This way, instead of having empty cells in the "ImageLink" field, you insert a link to a small transparent or white image that you create in advance.

For example, in Excel, instead of having empty fields for people without a photo, you can replace the empty cells with a URL to a white image (like C:\path\to\empty_image.jpg).


This approach ensures that the INCLUDEPICTURE field will never encounter an empty URL, thereby avoiding the error without requiring additional IF fields.


0
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 

Have you tried using an IF field without breaking the image link?

Field Insertion:

Always use this structure of the IF field, but without directly encapsulating the INCLUDEPICTURE in the IF:

{ INCLUDEPICTURE { IF { MERGEFIELD "ImageLink" } = "" "C:\\path\\to\\empty_image.jpg" { MERGEFIELD "ImageLink" } } \d }


0
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 

Here, if the image link is empty, a default image (for example, an empty image) is inserted.
If the link is valid, the MERGEFIELD field inserts the URL of the actual image.

0
NellyAblon Posted messages 10 Status Membre
 

So I just tried it, it works except that now instead of the error message a photo is displayed but not the empty image... we are making progress.

0
NellyAblon Posted messages 10 Status Membre
 

I feel like includepicture and if don't get along well!!!

0
NellyAblon Posted messages 10 Status Membre
 

I will try your answer, but to clarify, these are not empty fields in my database; I always have a link. In the label sheet, when there is no more data, the include picture field shows an error in the remaining empty labels on the page.

0
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 

Personally, I wouldn't have used INCLUDEPICTURE which is often temperamental, especially when combined with conditions in a mail merge.

A VBA script is more reliable and allows for finer control over the behavior of images.

However, you need to prepare your Excel file in advance. Make sure that in your Excel file, you have a column with the URLs of the images, and that you have other columns with the necessary information for the mail merge.

In the VBA editor, go to Insert > Module to create a new module.

Insert the following code:

Sub InsertImages() Dim doc As Document Dim r As Range Dim imgPath As String Dim i As Integer Dim dataField As String Dim imageCell As Range ' Initialize the active document Set doc = ActiveDocument ' Loop through all mail merge records For i = 1 To doc.MailMerge.DataSource.RecordCount ' Go to the current record doc.MailMerge.DataSource.ActiveRecord = i ' Get the image link from the data source imgPath = doc.MailMerge.DataSource.DataFields("ImageLink").Value ' Check if the image link is not empty If imgPath <> "" Then ' Select the field or cell where the image should be inserted Set r = doc.MailMerge.DataSource.DataFields("ImagePosition") ' Clear the current text if necessary r.Text = "" ' Insert the image in the cell or at the specified location doc.InlineShapes.AddPicture FileName:=imgPath, LinkToFile:=False, SaveWithDocument:=True, Range:=r End If Next i End Sub 

Modify the code to fit your needs

ImageLink refers to the column in your Excel file containing the image links.


ImagePosition represents the location in the document where you want the image to be inserted. You may need to adjust this part according to the structure of your Word document.

Then go to View > Macros > View Macros, select InsertImages, and then click "Run".

Advantages of this method


More flexibility: You can fully customize where and how the images are inserted.


Better error handling: If a link is invalid or missing, the macro can skip that image without causing a visible error.


No update issues: Unlike the INCLUDEPICTURE field, which often requires manual updating, the macro directly inserts the images into the document.


0
NellyAblon Posted messages 10 Status Membre
 

I already have this code in my VBA macro in Excel to launch my mail merge

Sub MailMerge() 'Call AddReference Dim DatabaseName As String Dim appWord As Object Set appWord = CreateObject("Word.application") Dim docWord As Object ' Path to the Excel file and the Word document DatabaseName = "G:\24-Office\01-Project Management\Nelly in progress\Cleaned Senators.xlsm" Dim WordDocPath As String WordDocPath = "G:\24-Office\01-Project Management\Nelly in progress\Merging 348 senators table - cleaned.docx" ' Create an instance of Word Set appWord = CreateObject("Word.Application") appWord.Visible = True ' Open the Word document Set docWord = appWord.Documents.Open(WordDocPath) ' Configure the mail merge With docWord.MailMerge .MainDocumentType = 1 ' Open the Excel database with the correct driver .OpenDataSource Name:=DatabaseName, _ Connection:="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabaseName & ";Extended Properties=""Excel 12.0 Macro;HDR=Yes;"";", _ SQLStatement:="SELECT * FROM [Base$] WHERE [Political_Group] = 'The Republicans' ORDER BY Quality DESC, Name" ' Specify the merge to a new document .Destination = wdSendToNewDocument .SuppressBlankLines = True ' Use all available records With .DataSource .FirstRecord = 1 .LastRecord = -16 End With ' Execute the mail merge operation .Execute Pause:=False End With appWord.Selection.wholestory appWord.Selection.Fields.Update ' Close the source document without saving docWord.Close False ' Release Word objects Set docWord = Nothing Set appWord = Nothing ' Enable screen updating Application.ScreenUpdating = True End Sub
0
NellyAblon Posted messages 10 Status Membre
 

Great, I'll give it a try, but how do I specify the location in my Word document?

I admit I'm a bit lost right now.

My goal would have been to fill in all the fields via VBA, but I'm a little confused... for example, first name, last name, knowing that I have the columns in my Excel file as well as the "Photo" column with the URL link for the photo.

Thank you so much for your help.

0
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 

Hello,

You need to use bookmarks or merge fields to specify the location where you want to insert images and other data.


For images, you can use a bookmark in the Word document, and the macro will use this bookmark to insert the image at that location.


For other data (first name, last name, etc.), Word will handle it automatically through standard merge fields.

Try using this modified macro instead:

Sub InsertImages() Dim doc As Document Dim imgPath As String Dim i As Integer Dim imageBookmark As Bookmark Dim mergeField As Field Dim nomField As Field, prenomField As Field ' Initializing the active document Set doc = ActiveDocument ' Start the mail merge, loop through all mail merge records For i = 1 To doc.MailMerge.DataSource.RecordCount ' Go to the current record doc.MailMerge.DataSource.ActiveRecord = i ' Get the image link from the data source imgPath = doc.MailMerge.DataSource.DataFields("Photo").Value ' Check if the image link is not empty If imgPath <> "" Then ' Check if the bookmark for the image exists (for example "ImagePlace") If doc.Bookmarks.Exists("ImagePlace") Then ' Insert the image at the bookmark "ImagePlace" Set imageBookmark = doc.Bookmarks("ImagePlace") ' Remove the current text from the bookmark (if it exists) imageBookmark.Range.Text = "" ' Insert the image at the position specified by the bookmark doc.InlineShapes.AddPicture FileName:=imgPath, LinkToFile:=False, SaveWithDocument:=True, _ Range:=imageBookmark.Range End If End If ' Update fields such as "First Name" and "Last Name" via standard mail merge For Each mergeField In doc.Fields If mergeField.Type = wdFieldMergeField Then If InStr(mergeField.Code.Text, "Nom") > 0 Then mergeField.Result.Text = doc.MailMerge.DataSource.DataFields("Nom").Value ElseIf InStr(mergeField.Code.Text, "Prenom") > 0 Then mergeField.Result.Text = doc.MailMerge.DataSource.DataFields("Prenom").Value End If End If Next mergeField Next i End Sub 

Bookmark for the image:

The macro now uses a bookmark (named "ImagePlace") to specify where the image should be inserted in the Word document. You need to manually add this bookmark in your Word document at the location where you want the image to appear.

Merge fields:

To insert data like first name and last name, you can add standard merge fields in your Word document. The macro loops through them and replaces the corresponding merge field values with data from the source.

Getting data from Excel:

The macro accesses your columns in Excel using doc.MailMerge.DataSource.DataFields("Column Name"). You need to ensure that the column names in Excel exactly match the names used in the macro.

Now you need to set up the Word document:


Insert a bookmark for the image:


Go to your Word document.
Place the cursor where you want the image to be inserted.
Go to the Insert tab > Bookmark, then name it "ImagePlace".


Add the merge fields:


In Word, go to the Mailings tab > Insert Merge Field.
Insert the fields First Name, Last Name, and any other columns you have in your Excel file.

When you run the macro, it will loop through each mail merge record, insert the image at the "ImagePlace" bookmark, and fill in the other fields (like first name and last name) with data from Excel.

This will allow you to customize your document with images and data for each mail merge record.


0
NellyAblon Posted messages 10 Status Membre
 

It’s not working. I don’t have a final merged document and on top of that, no photo is displayed in the bookmark

0
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 


All right, if the macro is not working as expected and is not producing a final merged document with the photos, this could be due to several factors.

Make sure the mail merge is ready.

Setup in Word


Merge fields: Your Word document must contain merge fields (<<Name>>, <<FirstName>>, etc.) in the appropriate locations to insert the data from Excel.


Bookmark for the image: Add a bookmark called "ImagePlace" in the Word document where you want the images to be inserted.

Here is a revised macro that correctly handles the merge process and image insertion.

Sub InsertImagesAndMerge() Dim doc As Document Dim imgPath As String Dim i As Integer Dim imageBookmark As Bookmark Dim mergedDoc As Document Dim mergeField As Field Dim dataSource As MailMergeDataSource ' Initialize the active document Set doc = ActiveDocument ' Execute the merge to create a new document with all records doc.MailMerge.Execute ' Retrieve the merged document Set mergedDoc = ActiveDocument ' Loop through each merged record in the final document Set dataSource = doc.MailMerge.DataSource For i = 1 To mergedDoc.MailMerge.DataSource.RecordCount ' Position on the correct record mergedDoc.MailMerge.DataSource.ActiveRecord = i ' Get the image link from the data source imgPath = mergedDoc.MailMerge.DataSource.DataFields("Photo").Value ' Check if the image link is not empty If imgPath <> "" Then ' Check if the bookmark for the image exists (e.g., "ImagePlace") If mergedDoc.Bookmarks.Exists("ImagePlace") Then ' Insert the image at the "ImagePlace" bookmark Set imageBookmark = mergedDoc.Bookmarks("ImagePlace") ' Remove current text from the bookmark imageBookmark.Range.Text = "" ' Insert the image at the position specified by the bookmark mergedDoc.InlineShapes.AddPicture FileName:=imgPath, LinkToFile:=False, SaveWithDocument:=True, _ Range:=imageBookmark.Range End If End If Next i End Sub 

Run the InsertImagesAndMerge macro.


The document will be merged and will generate a new file where each record will be processed, and the images will be inserted at the "ImagePlace" bookmark.

Checkpoints if it still doesn’t work:


Ensure the merge works: You should see your fields like <<Name>> and <<FirstName>> filled in correctly after the merge.


Image path: Check that the image paths are correct and accessible.


Bookmark present: Ensure that the "ImagePlace" bookmark exists in your document at the location where you want to insert the images.


0
NellyAblon Posted messages 10 Status Membre
 

Everything works except the image (no image) the bookmark is there and the paths are correct

0
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 

Alright, since everything works except for the image insertion, it's likely that the issue comes from the way the image is inserted at the bookmark location. I will suggest a more robust approach for inserting images using an alternative method to handle the bookmarks and image paths.

I'll be back.


0
Bruno83200_6929 Posted messages 707 Registration date   Status Membre Last intervention   168
 

Update of the macro for inserting images

Sub InsertImagesAndMerge() Dim doc As Document Dim imgPath As String Dim i As Integer Dim imageBookmark As Bookmark Dim mergedDoc As Document Dim dataSource As MailMergeDataSource Dim imageRange As Range ' Initialization of the active document Set doc = ActiveDocument ' Execute the merge to create a new document with all records doc.MailMerge.Execute ' Retrieve the merged document Set mergedDoc = ActiveDocument ' Loop through each merged record in the final document For i = 1 To mergedDoc.MailMerge.DataSource.RecordCount ' Go to the current record mergedDoc.MailMerge.DataSource.ActiveRecord = i ' Get the image link from the data source imgPath = mergedDoc.MailMerge.DataSource.DataFields("Photo").Value ' Check if the image link is not empty and the image exists If imgPath <> "" And Dir(imgPath) <> "" Then ' Check if the bookmark for the image exists (e.g. "ImagePlace") If mergedDoc.Bookmarks.Exists("ImagePlace") Then ' Retrieve the range of the bookmark Set imageRange = mergedDoc.Bookmarks("ImagePlace").Range ' Delete the current bookmark to avoid conflicts during insertion mergedDoc.Bookmarks("ImagePlace").Delete ' Insert the image at the location of the bookmark mergedDoc.InlineShapes.AddPicture FileName:=imgPath, LinkToFile:=False, SaveWithDocument:=True, _ Range:=imageRange End If End If Next i End Sub 

The line If imgPath <> "" And Dir(imgPath) <> "" Then checks that the image link is not empty and that the image actually exists at the specified location before attempting to insert it.

If the bookmark exists, it is deleted just before inserting the image in its place. This prevents the bookmark from remaining in the document and causing issues during insertion.

The range of the bookmark (Range) is used to insert the image at the exact location where the bookmark was situated, even after the bookmark has been deleted.

Additional step to check


Check image paths: Ensure that the image paths in Excel are correct and point to existing image files (JPG, PNG format, etc.).

Run the macro

If the bookmark "ImagePlace" is correctly placed, the macro will now insert the image at the correct location.
Also test with a local image to avoid any issues related to permissions or incorrect paths.

If you want to quickly test if the image path is correct, you can add this line in the macro to display the path in a message box before inserting each image:

MsgBox "Image path: " & imgPath 

This allows you to visually check that the correct path is being used for each image.


0