Kingler
Kingler

Reputation: 5

Mail merging into Microsoft Word text boxes with C#

I have a word document, that uses several textboxes, which contain mail merge fields.

I want to mail merge programmatically into a word document, by using a system that I have made, that searches for any mail merge fields in a document and then inserts the appropriate value into the mail merge fields and then saves the document as a new file.

By using

Document.StoryRanges

I am able to do the above process for 1 text box.

But if I make several text boxes, it only seems to insert the value into one of the textboxes consistently. The texbox that receives the value does not change. If I try to delete that textbox, the mail merging process does not work and then I have to fiddle with some of the other textboxes to get it to work. For example I have to bring the textbox backwards and then forwards for the system to mail merge into only of the textboxes.

I have tried creating a foreach loop to go into each textbox, without much success. So I did some debugging and found that the system is only reading the entire document and one of the textboxes as StoryRanges.

Upvotes: 0

Views: 1701

Answers (1)

powersof10b
powersof10b

Reputation: 31

Here's a solution I used recently. You can get to the mail merge fields through Document.Shapes. I'm not sure exactly what's going on here, but it worked for me.

public static List<Field> getMailMergeFields(Document document)
{
    List<Field> mailMergeFields = new List<Field>();
    foreach (Shape shape in document.Shapes)
    {
        if (shape.TextFrame.HasText != 0)
        {
            foreach (Field field in shape.TextFrame.ContainingRange.Fields)
            {
                if (isMailMergeField(field)) mailMergeFields.Add(field);
            }
        }
    }
    foreach (Field field in document.Fields)
    {
        if (isMailMergeField(field)) mailMergeFields.Add(field);
    }
    return mailMergeFields;
}

public static bool isMailMergeField(Field field)
{
    string fullField = field.Code.Text.Trim();
    if (!fullField.StartsWith("MERGEFIELD")) return false;
    if (!fullField.EndsWith(@"\* MERGEFORMAT")) return false;
    return true;
}

Hope this helps.

Upvotes: 1

Related Questions