JvRossum
JvRossum

Reputation: 1008

Obtain value from mergefield C# Word VSTO

The title says all, but I'll explain more in detail. Here is the thing.

I'm currently developing extra code in a Word VSTO add-in which uses mergefields in a template. The mergefields in the template are filled using data from an external file. What I need is to read the value from a Merge Field but I have totally no clue how to accomplish this. I've been searching for a few days now but none of the articles I read worked for me...

So the question:

How can I get the value from a specific merge field in Word using VSTO?

Upvotes: 1

Views: 1587

Answers (1)

Kiru
Kiru

Reputation: 3565

Mailmerge is quite simple in VSTO, Here is the two magic lines that will do

//Pass in the path of external file    
document.MailMerge.OpenDataSource(Name: vm.FilePath.FullName);
document.MailMerge.Destination = WdMailMergeDestination.wdSendToNewDocument;

I found another full example here

This codeblock retrieves all fields in the document

public static List<string> GetFieldsUsedInDocument(Document document)
        {
            var fields = new List<string>();

            foreach (MailMergeField fld in document.MailMerge.Fields)
            {
                if (fld.Code != null)
                {
                    fields.Add(fld.Code.Text.ToUpper());
                }
            }
            return fields;
        }

To get the MergeField names from the list of fields returned above GetFieldsUsedInDocument

 public static List<string> GetMergeFields(List<string> allFields)
        {
            var merges = new List<string>();

            foreach (var field in allFields)
            {
                var isNestedField = false;
                foreach (var fieldChar in field)
                {
                    int charCode = fieldChar;
                    if (charCode == 19 || charCode == 21)
                    {
                        isNestedField = true;
                        break;
                    }
                }
                if (!isNestedField)
                {
                    var fieldCode = field;
                    if (fieldCode.Contains("MERGEFIELD"))
                    {
                        var fieldName = fieldCode.Replace("MERGEFIELD", string.Empty).Replace('"', ' ').Trim();
                        var charsToGet = fieldName.IndexOf(" ");
                        if (charsToGet < 0)
                            charsToGet = fieldName.IndexOf(@"\");

                        charsToGet = charsToGet > 0 ? charsToGet : fieldName.Length;

                        fieldName = fieldName.Substring(0, charsToGet);

                        if (!merges.Contains(fieldName))
                        {
                            merges.Add(fieldName);
                        }
                    }
                }
            }
            return merges;
        }

Upvotes: 2

Related Questions