• Word Mailmerge Tips & Tricks

    Author
    Topic
    #495501

    Introduction
    The following tips are written with a view to addressing a wide range of common problems people have with mailmerges. Please read them and see if your issues are addressed before asking for help. You might find a quicker solution this way than waiting for someone to respond to a post.

    There are also four useful macros towards the end of this thread, to:
    • Send Mailmerge Output to Individual Files;
    • Run a Mailmerge from Excel, Sending the Output to Individual Files
    • Split Merged Output to Separate Documents; and
    • Convert Text Representations of Fields to Working Fields.
    For PC macro installation & usage instructions, see: http://www.gmayor.com/installing_macro.htm.
    For Mac macro installation & usage instructions, see: http://word.mvps.org/Mac/InstallMacro.html

    Note 1: The field brace pairs (i.e. ‘{ }’) for the following examples are all created in the mailmerge main document itself, via Ctrl-F9 (Cmd-F9 on a Mac); you can’t simply type them or copy & paste them from this thread or another website. Nor is it practicable (for the most part) to add them via any of the standard Word dialogues. Likewise, you can’t type or copy & paste the chevrons (i.e. ‘« »’) – they’re part of the actual mergefields, which you can insert from the ‘Insert Merge Field’ dropdown. The spaces represented in the field constructions are all required. Instead of the →, ↵ and ¶ symbols shown in the examples, you should use real tabs and line/paragraph breaks, respectively.

    Note 2: For a macro to convert any of the text-fields below into working fields in your document, scroll to the bottom of this page.

    Note 3: Mailmerge previews are not a reliable indicator of how many of the following fields will work when the merge is executed, especially where conditional output is concerned. For testing & validation purposes, always send the output to a new document.

    Note 4: References in the examples to file paths and mergefield names will need to be replaced with the actual paths and mergefield names, respectively.

    Mailmerge Data Format Problems
    By default, Word 2002 & later use the OLE DB provider to get merge fields and records from the data source. Because the OLE DB provider is designed to return data in a way that is compatible with Access and other relational database packages, it requires a specific data type for each field, and every record in that field must be of that data type. When using data sources that aren’t databases, the OLE DB provider queries the first 8 records are used to determine the data type for each field (the 8 can be changed in the Windows Registry, but it’s not advisable to do so). This can lead to unexpected results with data sources such as Excel workbooks, where cells (records) in a column (field) can have different data types. When the OLE DB provider gets data from a column with mixed data types, records that don’t conform to the determined data type for the column are liable to not be handled correctly. To complicate matters, there are two text data types: “text” (up to 255 characters) and “memo” (can be longer than that).

    Some common mailmerge issues arising out of this include:
    • Numbers but not text or dates being output for some records; and
    • Text data being truncated at 255 characters.

    Ideally, one would ensure each field has only one data type. Workarounds include:
    • Inserting a dummy first record containing data in the format that is not being output correctly; or
    • Reordering the data so the first record has content in the format that is not otherwise being output correctly.
    Thus, if numbers appear but text and/or dates don’t, ensure the first record for that field has text or a date. Similarly, if text over 255 characters is being truncated, ensure the first record for that field contains more than 255 characters.

    Although adding field switches to the mailmerge main document is the preferred method of controlling the output format (amongst other things it allows the mailmerge to format the data differently than the source), you can also preserve the source data’s formatting by using Dynamic Data Exchange (DDE). This is only useful, though, if the mailmerge data are in the first sheet in the workbook and the data start on the first row of that sheet. To choose the DDE data transfer method when you’re connecting to an Excel worksheet during a mail merge, all you have to do is select one check box in Word:
    • In Word 2003 & earlier, on the Word Tools menu, click on Tools|Options|General;
    • In Word 2007, click on Office Button|Options|Advanced>General;
    • In Word 2010 & later, click on File|Options|Advanced>General,
    then check the ‘Confirm conversion at Open’ option.

    At the step in the mail-merge process where you connect to your data file, after you locate the file you want to connect to, the Confirm Data Source dialog box opens. Click “Application via DDE (*.???)”, and then click OK. In the Application dialog box, select the table/range that contains the information you want to merge, and then click OK. The data will now be formatted the same in your merged documents as they look in the source file.

    Although the Windows DDE dialog box allows and presents range names for the data source, it only presents names that reference the first sheet and have either Workbook scope or the same scope as the sheet.

    Note: It’s probably a good idea to turn off the Confirm conversion at Open option after you finish your mail merge. Otherwise, you might be prompted to confirm your data source at times when that’s the last thing you want to worry about.

    Another common source of confusion is the failure of a mailmerge to retain attributes like font formatting in Excel data sources. That occurs because mailmerges work with data values and data types (i.e. text, date, number, etc.) only, regardless of whether the data source is an Excel workbook, a Word table, an Access database, or a text file. Formatting like font colours, background shading, etc. are neither data values nor data types.

    Test Whether a Text Mergefield Contains Numeric Data
    The following field code allows you to test whether a given mergefield is text or numeric. This is useful if the field can contain mixed data and you want to control the formatting of the data.

    {QUOTE{SET Val {MERGEFIELD Data}}{IF{REF Val}= {=Val} “{Val} is Numeric” “{Val} is Text”}}

    and so:

    {QUOTE{SET Val {MERGEFIELD Data}}{IF{REF Val}= {=Val} {=Val # 0.00} {REF Val}}}

    Note 1: This approach fails if the numeric data have more than a 13 digit decimal.

    Note 2: This approach is not intended to address problems cause by having text data in fields the mailmerge process has already determined to be numeric (see Mailmerge Data Format Problems above).

    Convert Mailmerge Date Fields to Plain Text
    The DATE field ordinarily survives the mailmerge process and remain active in the output document, which can be problematic, since such fields update to the current date every time you open the document. Conversely, CREATEDATE fields from the mailmerge main document reflect that document’s creation date (not that of the mailmerge output).
    To force DATE fields to convert to their results (ie so that they become static dates), reflecting the date on which the merge was performed, simply embed them in a QUOTE field coded along the lines of:

    {QUOTE{DATE}}

    plus any formatting switches you might want for the date format.

    Managing Mailmerge Graphics
    To insert variable images in a mailmerge, you need to embed the relevant mailmerge field in a INCLUDEPICTURE field. However, there are some issues with this that make the process less straightforward than one might expect. For example, when embedding a mailmerge field in an INCLUDEPICTURE field for the purpose of merging graphics:
    1. the file paths to the fields need to have the separators expressed as ‘\’ instead of the usual ”;
    2. the pictures usually won’t show until you refresh the fields (eg Ctrl-A, then F9) in the output document after completing the merge; and
    3. even after updating the images, they remain linked to the image files, which can be an issue if you later delete the image or you need to send the merged output to someone else.

    The following field constructions and accompanying macro address all three issues (i.e. you don’t need to do anything special to the paths, or refresh the fields, and they’ll no longer be linked to the source files):

    • If the path to the images isn’t included in the data source and you can’t be sure they will always be in the same folder as the mailmerge main document, you could use a field coded as:

    {INCLUDEPICTURE {IF TRUE “C:UsersMy Document PathPictures«Image»”} d}
    or:
    {INCLUDEPICTURE {IF TRUE “C:UsersMy Document PathPictures{MERGEFIELD Image}”} d}

    • If the path to the images is held in a separate field in the mailmerge data source, you could use:

    {INCLUDEPICTURE {IF TRUE “«FilePath»«Image»”} d}
    or:
    {INCLUDEPICTURE {IF TRUE “{MERGEFIELD FilePath}{MERGEFIELD Image}”} d}

    Note: You need a path separator between the filepath mergefield and the image mergefield. If that separator is included in the source data, it can be omitted from the field above construction but leaving it there has no adverse effects either.

    • If the path to the images is held in the same field as the image name in the mailmerge data source, you could use:

    {INCLUDEPICTURE {IF TRUE “«Image»”} d}
    or:
    {INCLUDEPICTURE {IF TRUE “{MERGEFIELD Image}”} d}

    • If the path to the images isn’t included in the data source but you can be sure they will always be in the same folder as the mailmerge main document, you can incorporate a FILENAME field thus:

    {INCLUDEPICTURE {IF TRUE “{FILENAME p}..{MERGEFIELD Image}”} d}
    or:
    {INCLUDEPICTURE {IF TRUE “{FILENAME p}..«Image»”} d}

    By adding the following macro to your mailmerge main document, clicking on the ‘Edit Individual Documents’ button will intercept the merge, finishing it and unlinking the pictures (and any other residual fields except for hyperlinks).
    [Code]Sub MailMergeToDoc()
    Application.ScreenUpdating = False
    Dim i As Long
    ActiveDocument.MailMerge.Execute
    With ActiveDocument
    For i = .Fields.Count To 1 Step -1
    If .Fields(i).Type wdFieldHyperlink Then .Fields(i).Unlink
    Next
    End With
    Application.ScreenUpdating = True
    End Sub[/Code]
    If you’re using Word 2007 or later, your mailmerge main document will need to be saved in the .doc or .docm formats, as documents using the .docx format cannot contain macros. The potential disadvantage of intercepting the ‘Edit Individual Documents’ process this way is that you no longer get to choose which records to merge at that stage. However, you can still achieve the same outcome – and with greater control – via the ‘Edit Recipient List’ tools.

    For what it’s worth, *provided* the path has the separators expressed as ‘\’, you can retain the links by omitting the macro.

    Mailmerge Hyperlink ‘Click Here’ Insertion
    By default, if you insert a mailmerge field into a hyperlink field, the hyperlinks will all show the first record’s address as the ‘Text to display’ text. Here’s how you can do get a mailmerge to display your preferred default ‘Text to display’ text instead:
    1. Disregarding mergefield issues for the moment, insert a hyperlink into the document in the normal way, choosing whatever ‘Click Here’ text you want in the ‘Text to display’ box.
    2. Select the inserted hyperlink and press Shift-F9 to expose its field code.
    3. Replace everything in the field after ‘HYPERLINK’ with your mergefield.
    4. Select the field and press F9 to update the display.

    In Word 2007 & later, you can make the display text variable also, by following these additional steps:
    5. Position the cursor anywhere within the display text.
    6. Insert a mergefield pointing to whatever data field you want to use for the display text (this could even be the same field as used at step 3 above).
    7. Delete all of the previous display text either side of your last-inserted mergefield (note that this field will likely have updated already).
    8. Execute the merge.
    9. After merging to a new document, use Ctrl-A, F9 to update all fields. Without this, the mergefield hover text won’t update to the correct targets.

    Note: The above is only for merged output sent to a new document; it does not work with merges to email or print. For merges to email, see: https://support.microsoft.com/en-us/kb/912679

    Note: Hyperlink fields modified this way are liable to cease functioning once the merge has been executed. Accordingly, it’s best to save mailmerge main document before doing the merge and not re-save it afterwards. If you need to make changes to the mailmerge main document, don’t make/save them after doing a merge; make/save them beforehand.

    Conditionally Merge Spouse Data
    The following construction can be used to manage data where some recipients may be living in a marital relationship with the same or different surnames.

    {MERGEFIELD First_Name}{MERGEFIELD Middle_Name b ” “} {IF{MERGEFIELD Spouse_First_Name}= “” {MERGEFIELD Last_Name} {IF{MERGEFIELD Spouse_Last_Name}= {MERGEFIELD Last_Name} “and {MERGEFIELD Spouse_First_Name}{MERGEFIELD Spouse_Middle_Name b ” “} {MERGEFIELD Last_Name}” {IF{MERGEFIELD Spouse_Last_Name}= “” “and {MERGEFIELD Spouse_First_Name}{MERGEFIELD Spouse_Middle_Name b ” “} {MERGEFIELD Last_Name}” “{MERGEFIELD Last_Name} and {MERGEFIELD Spouse_First_Name}{MERGEFIELD Spouse_Middle_Name b ” “} {MERGEFIELD Spouse_Last_Name}”}}}

    Merge Multiple Fields, Using Commas and ‘And’
    The following construction can be used to manage data where one or more related fields (A, B, C, D, E, & F) may or may not be populated.

    {MERGEFIELD A}{IF{MERGEFIELD C}= “” ” and {MERGEFIELD B}” “, {MERGEFIELD B}{IF{MERGEFIELD D}= “” ” and {MERGEFIELD C}” “, {MERGEFIELD C}{IF{MERGEFIELD E}= “” ” and {MERGEFIELD D}” “, {MERGEFIELD D}{IF{MERGEFIELD F}= “” ” and {MERGEFIELD E}” “, {MERGEFIELD E} and {MERGEFIELD F}”}”}”}”}

    Note: It is assumed that none of the fields after the first empty one will be populated.

    Mailmerge CheckBox Insertion
    To use a mergefield to toggle the state of a checkbox, insert an IF field coded as:

    {IF{MERGEFIELD CheckState}= “X” {SYMBOL 254 f Wingdings u } {SYMBOL 253 f Wingdings u }}
    or:
    {IF«CheckState»= “X” {SYMBOL 254 f Wingdings u } {SYMBOL 253 f Wingdings u }}

    where ‘CheckState’ is the name of the mergefield used to determine the checkbox status and ‘X’ is the field value that toggles it ‘checked’.

    Mailmerge String Formatting
    to control mailmerge string formatting, add a ‘Charformat’ picture switch to the mergefield as follows:
    1. select the mergefield;
    2. press Shift-F9 to expose the field coding. It should look something like {MERGEFIELD MyData}, where ‘MyData’ is your data field’s name;
    3. delete everything between ‘MyData’ and the closing field brace;
    4. add ‘ * Charformat’ after ‘MyData’, so that you end up with {MERGEFIELD MyData * Charformat};
    5. format at least the ‘M’ in ‘MERGEFIELD’ with the font attributes you want;
    6. position the cursor anywhere in the field and press F9 to update it.

    Mailmerge Number & Currency Formatting
    To control number & currency formatting in Word, add a numeric picture switch to the mergefield. To do this:
    1. select the mergefield;
    2. press Shift-F9 to reveal the field coding. It should look something like {MERGEFIELD MyData};
    3. edit the field so that you get {MERGEFIELD MyData # $,0.00} (or whatever other numeric format you prefer – see below);
    4. position the cursor anywhere in this field and press F9 to update it.

    Note 1: The ‘# $,0.00′ in the field is referred to as a numeric picture switch. Other possibilities include:
    • # 0 for rounded whole numbers
    • # ,0 for rounded whole numbers with a thousands separator
    • # ,0.00 for numbers accurate to two decimal places, with a thousands separator
    • # $,0 for rounded whole dollars with a thousands separator
    • # “$,0.00;($,0.00);’-‘” for currency, with brackets around negative numbers and a hyphen for 0 values

    Note 2: The precision of the displayed value is controlled by the ‘0.00’. You can use anything from ‘0’ to ‘0.000000000000000’.
    If you use a final ‘;’ in the formatting switch with nothing following, (eg # “$,0.00;($,0.00);”) zero values will be suppressed. Note that this suppresses 0s resulting from empty fields and from fields containing 0s.

    Note 3: If you use a decimal tab or right-aligned tab to align the values, wrap the switch in quotes (i.e. # “$,0.00”) and insert a tab into the field code after the $ sign, you can have the values output with the decimal alignment occurring after the $ sign.

    Force ‘0’ Substitution for Empty/Missing Records
    There is a variety of ways to force the substitution of 0 for missing records. For example:
    1. select your mergefield, which will look something like «Value»
    2. press Ctrl-F9 to embed your mergefield in another field, so that you get {«Value»}
    3. type ‘Set Val’ into the {«Value»} field, so that you end up with {Set Val «Value»}
    4. after the newly-inserted field, press Ctrl-F9 again to insert another (empty) field, so that you get {Set Val «Value»}{ }
    5. type ‘=Val # “$,0.00″‘ into the second field, so that you end up with {Set Val «Value»}{=Val # 0}
    6. position the cursor anywhere in this field and press F9 to update it.
    Alternatively:
    1. insert a pair of your mergefields so you see something like «Value» «Value»
    2. select both mergefields.
    3. press Ctrl-F9 to embed both mergefield in another field, so that you get {«Value» «Value»}
    4. fill in the field, so that you end up with {IF«Value»= “” 0 «Value»}
    5. position the cursor anywhere in this field and press F9 to update it.
    Yet another approach is to:
    1. select your mergefield, which will look something like «Value».
    2. press Ctrl-F9 to embed your mergefield in another field, so that you get {«Value»}
    3. type ‘QUOTE 0″‘ into the {«Value»} field before the «Value» and ‘”‘ after it, so that you end up with {QUOTE “0«Value»”}
    4. position the cursor anywhere in this field and press F9 to update it.
    This last approach works by prepending the mergefield’s result with a 0, so the results of any calculations should be the same.

    Basic Mailmerge Maths
    You can create the formula in Word to perform maths on a mergefield. For example, suppose your data include the final price of an item for which you need to show how much is the base price and how much is the tax component, where the tax is 10% of the base price (ie 1/11th of the final price):
    1. select your mergefield, which will look something like «Price»;
    2. press Ctrl-F9 to wrap another field around it, thus { «Price» };
    3. to calculate the tax component, edit the field so that you get {=«Price»/11 # “$,0.00”};
    4. to calculate the base price, edit the field so that you get {=«Price»*10/11 # “$,0.00”};
    5. position the cursor anywhere in this field and press F9 to update it.

    Note: the precision of the displayed value is controlled by the ‘0.00’. You can use anything from ‘0’ to ‘0.000000000000000’.

    To see how to do a wide range of calculations in Word, check out my Microsoft Word Field Maths Tutorial, available in the ‘Sticky’ thread at the top of the Word forum:
    http://www.msofficeforums.com/word/38720-microsoft-word-field-maths-tutorial.html

    Dealing With Null Values in Mailmerge Arithmetic
    If your source data sometimes has empty fields, a formula referencing those fields is liable to fail with a Syntax Error. For example:

    {={MERGEFIELD Data1}+{MERGEFIELD Data2} # 0}

    will fail in such cases. You can overcome this by testing each mergefield and replacing any nulls with 0s, as in:

    {={IF{MERGEFIELD Data1}= “” 0 {MERGEFIELD Data1}}+{IF{MERGEFIELD Data2}= “” 0 {MERGEFIELD Data2}}}

    or by coding the field along the lines of:

    {QUOTE{SET Val1 {MERGEFIELD Data1}}{SET Val2 {MERGEFIELD Data2}}{=Val1+Val2 # 0}}

    Mailmerge Percentage Formatting
    To control percentage formatting in Word, add a formula and numeric picture switch to the mergefield, as follows:
    1. select your mergefield, which will look something like «Percent»;
    2. press Ctrl-F9 to wrap another field around it, thus { «Percent» };
    3. edit the field so that you get {=«Percent»*100 # 0.00%};
    4. position the cursor anywhere in this field and press F9 to update it;
    5. run your mailmerge.

    Note: the precision of the displayed value is controlled by the ‘0.00’. You can use anything from ‘0’ to ‘0.000000000000000’.

    Mailmerge Phone Number Formatting
    To control Phone Number formatting in Word, all you need to do is to add a picture switch to the mergefield, as follows:
    1. select the mergefield;
    2. press Shift-F9 to expose the field coding. It should look something like {MERGEFIELD MyData}, where ‘MyData’ is your data field’s name;
    3. delete everything between ‘MyData’ and the closing field brace;
    4. add ‘ # “(000) 0000 0000″‘ after ‘MyData’, so that you end up with {MERGEFIELD MyData # “(000) 0000 0000”};
    5. position the cursor anywhere in this field and press F9 to update it.

    Mailmerge Date Formatting
    Word has a number of different methods of connecting to mail merge data sources, including DDE and OLE DB. Word 2002 and later use the OLE DB connection by default, though you can change this (to DDE, for example). To work around a limitation in the OLE DB provider used to get data from Excel etc., when Word is connected to an OLE DB data source, it treats dates as if they are in the US mm/dd/yyyy format, regardless of the format in Excel, your regional settings etc. Applying a date format switch fixes that – and gives the mailmerge document the ability to format the date independently of whatever format is used in the data source.
    To get the date format you want, you can add a formatting picture switch as follows:
    1. select the mergefield;
    2. press Shift-F9 to expose the field coding. It should look something like {MERGEFIELD MyDate} where ‘MyDate’ is your mergefield’s name;
    3. delete anything appearing after the mergefield’s name and add ‘@ “d MMMM yyyy”‘ to the field, as in {MERGEFIELD MyDate @ “d MMMM yyyy”}. With this switch your dates will come out like ‘2 August 2008’.
    4. position the cursor anywhere in this field and press F9 to update it.

    Other possible date formatting switches include:
    • @ “dddd, d MMMM yyyy”;
    • @ “ddd, d MMMM yyyy”;
    • @ “d MMM yyyy”;
    • @ “dd/MMM/yyyy”;
    • @ “d-MM-yy”.

    Note: You can swap the d, M, y expressions around, but you must use uppercase ‘M’ sequences for months – lowercase ‘m’ sequences are for minutes.

    Mailmerge Date Calculations
    To see how to do just about everything you might want to do with dates in Word, check out my Microsoft Word Date Calculation Tutorial, available in the ‘Sticky’ thread at the top of the Word forum:
    http://www.msofficeforums.com/word/38719-microsoft-word-date-calculation-tutorial.html
    For mailmerges, in particular, look at the item titled ‘Date and Time Calculations In A Mailmerge’. Do read the document’s introductory material, as it contains important information regarding configuring the fields for different date formats.

    Mailmerge Time Formatting
    To get the time format you want, you can add a formatting picture switch as follows:
    1. select the mergefield;
    2. press Shift-F9 to expose the field coding. It should look something like {MERGEFIELD MyTime} where ‘MyTime’ is your mergefield’s name;
    3. delete anything appearing after the mergefield’s name and add ‘@ “h:m”‘, as in {MERGEFIELD MyTime @ “h:m am/pm”};
    4. if you want the hours and/or minutes to display leading 0s, change ‘h’ to ‘hh for hours and ‘m’ to ‘mm’ for minutes;
    5. position the cursor anywhere in this field and press F9 to update it.

    Note: you must use lowercase ‘m’s for minutes – uppercase ‘M’s are for months.

    Mailmerge US Social Security Number Formatting
    The following field suppresses all except the last four digits in a mergefield where the data are formatted as ‘123-45-6789’.

    {QUOTE{SET ID {MERGEFIELD SSN}}{SET Part3 {=({ID}*(-1)-ID)/2}}”XXX-XX-“{Part3 # 0000}}

    Mailmerge US Zip Code Formatting
    The following field code correctly formats 5-digit and 5+4-digit Zip Code data, even where the source data may have incorrect formatting such as a hyphen followed by trailing 0s after plain 5-digit Zip Codes (eg because a db only accepts Zip Codes in the 5+4-digit format) or is formatted as a 5-digit or 9-digit string without hyphens.

    {QUOTE
    {SET Zip {MERGEFIELD ZipCode}}
    {IF{Zip}> 99999 {SET Zip {Zip # “00000′-‘0000”}}}
    “{=-{=-{Zip}-Zip}/2 # 00000;;}{=-({Zip}*(-1)-Zip)/2 # ;-0000;}”}

    Note: the line breaks depicted here are not needed – they’re just used to help with visualizing the code’s structure.

    Mailmerge String Testing
    You can test the contents of a mergefield by doing the following:
    1. select the field and Press Ctrl-F9 to enclose it in a new field, thus {«MyData»};
    2. fill in around the new field braces so that you end up with: {IF«MyData»= “Test String” “String/field to output if True” “String/field to output if False”};
    3. position the cursor anywhere in this field and press F9 to update it.

    Test Whether a Mergefield Contains a Given String
    When doing a mailmerge, the ‘If The Else’ Rules offer the following options in the drop down menu:
    • Field Name Equal To
    • Field Name Not Equal To
    • Field Name Less Than
    • Field Name Greater Than
    • Field Name Less Than or Equal
    • Field Name Great Than or Equal
    • Field Name is Blank
    • Field Name is Not Blank
    Word doesn’t have a ‘Field Name Contains’ option. The simple reason is that Word has no such field. That said, there are limited ways for testing whether a field contains a given string.

    For example a field coded as:

    {IF{MERGEFIELD MyField}= “MyText*” “True” “False”}
    or:
    {IF«MyField»= “MyText*” “True” “False”}

    tests whether the results of the mergefield starts with ‘MyText’

    Similarly, a field coded as:

    {IF{MERGEFIELD MyField}= “*MyText” “True” “False”}
    or:
    {IF«MyField»= “*MyText” “True” “False”}

    tests whether the results of the mergefield ends with ‘MyText’

    You can also test whether the text you’re interested in exists a pre-defined number of characters from the start or end. Thus, a field coded as:

    {IF{MERGEFIELD MyField}= “???MyText*” “True” “False”}
    or:
    {IF«MyField»= “???MyText*” “True” “False”}

    tests whether the results of the mergefield contains any three characters followed by ‘MyText’

    Similarly, a field coded as:

    {IF{MERGEFIELD MyField}= “*MyText???” “True” “False”}
    or:
    {IF«MyField»= “*MyText???” “True” “False”}

    tests whether the results of the mergefield ends with any three characters after ‘MyText’.

    If a mergefield contains a mix of alpha-numeric text, with only a single, non-zero, number, you can extract that number for testing via a field switch such as:

    {MERGEFIELD MyField # 0} (with the appropriate decimal provisions, if any)

    or ,via a formula such as:

    {={MERGEFIELD MyField}}
    or:
    {=«MyField»}

    Having extracted the number, you can then test its value or perform other mathematical functions on in it the normal way. To see how to do a wide range of calculations in Word, check out my Microsoft Word Field Maths Tutorial, available in the ‘Sticky’ thread at the top of the Word forum:
    http://www.msofficeforums.com/word/38720-microsoft-word-field-maths-tutorial.html

    Mailmerge Empty Space Suppression
    On PCs, you can use the mergefield b and/or f switches to suppress a space before or after an empty mergefield. For example, suppose you have:

    «Title» «FirstName» «SecondName» «LastName»

    but «SecondName» is sometimes empty and you don’t want that to leave two spaces in the output. To deal with that:
    1. select the «SecondName» field and press Shift-F9 so that you get {MERGEFIELD SecondName};
    2. edit the field code so that you end up with-

    {MERGEFIELD SecondName f ” “}
    or:
    {MERGEFIELD SecondName b ” “}

    depending on whether the space to be suppressed is following or before the mergefield;
    3. delete, as appropriate, the corresponding space following or before the mergefield;
    4. position the cursor anywhere in this field and press F9 to update it.

    Note: the b and f switches don’t work on Macs or in conjunction with other switches. In such cases you need to use and IF test instead, coded along the lines of:

    {IF{MERGEFIELD SecondName} “” ” {MERGEFIELD SecondName}”}
    or:
    {IF{MERGEFIELD SecondName} “” “{MERGEFIELD SecondName} “}

    Even so, you can use the b and f switches to express other mergefields that do have switches of their own. For example, suppose you have four fields ‘Product’, ‘Supplier’, ‘Quantity’ and ‘UnitPrice’, and you don’t want to output the ‘Product’, ‘Quantity’ or ‘UnitPrice’ fields if the ‘Supplier’ field is empty. In that case, you might use a field coded along the lines of:

    {MERGEFIELD “Supplier” b “{MERGEFIELD Product}→” f “→{MERGEFIELD Quantity # 0}→{MERGEFIELD UnitPrice # “$0.00”}¶
    “}

    Mailmerge Empty Line Suppression
    On PCs, you can use the mergefield b and/or f switches to suppress a paragraph break (or a line break) before and/or after an empty mergefield.
    Suppose you have:

    «Title» «FirstName» «LastName»
    «CompanyName»
    «Address1»
    «Address2»
    «City», «State» «Zip»

    but «Address2» is sometimes empty. To deal with that:
    1. select the «Address2» field and press Shift-F9 so that you get {MERGEFIELD Address2};
    2. edit the field code so that you get {MERGEFIELD Address2 f “”} or {MERGEFIELD Address2 b “”}, depending on whether the line to be suppressed is following or before the mergefield;
    3. move the paragraph break or line break to be suppressed into field code so that you end up with-

    {MERGEFIELD Address2 f “¶
    “}
    if you move the break following the field, or, if you move the break preceding the field:
    {MERGEFIELD Address2 b “¶
    “}

    4. position the cursor anywhere in this field and press F9 to update it.

    Note: the b and f switches don’t work on Macs, in conjunction with other switches, or if the field being tested contains spaces etc. when nominally ’empty’. In such cases you need to use and IF test instead, coded along the lines of:

    {IF{MERGEFIELD Address2} “” “{MERGEFIELD Address2}¶
    “}}
    or:
    {IF{MERGEFIELD Address2} “” “¶
    {MERGEFIELD Address2}”}}

    Conditionally Format Mailmerge Output
    To conditionally format mergefield outputs, you could use a series of fields coded as:

    {IF«MyField»= “0” «MyField» * Charformat}
    {IF«MyField»= “1” «MyField» * Charformat}
    {IF«MyField»= “2” «MyField» * Charformat}
    {IF«MyField»= “3” «MyField» * Charformat}
    {IF«MyField»= “4” «MyField» * Charformat}
    {IF«MyField»= “5” «MyField» * Charformat}

    where the ‘I’ in each ‘IF’ is formatted the way you want the output to appear.

    Similarly, to conditionally format text that varies according to mergefield outputs, you could use a series of fields coded as:

    {IF«MyField»= “0” “Text for 0” * Charformat}
    {IF«MyField»= “1” “Text for 1” * Charformat}
    {IF«MyField»= “2” “Text for 2” * Charformat}
    {IF«MyField»= “3” “Text for 3” * Charformat}
    {IF«MyField»= “4” “Text for 4” * Charformat}
    {IF«MyField»= “5” “Text for 5” * Charformat}
    or:
    {IF«MyField»= “0” “Plain Text and coloured text for 0“}
    {IF«MyField»= “1” “Plain Text and coloured text for 1“}
    {IF«MyField»= “2” “Plain Text and coloured text for 2“}
    {IF«MyField»= “3” “Plain Text and coloured text for 3“}
    {IF«MyField»= “4” “Plain Text and coloured text for 4“}
    {IF«MyField»= “5” “Plain Text and coloured text for 5“}

    The advantage of the second approach is the ability to mix the formats of the output.

    Note 1: Although the above examples use coloured text, you can use whatever text formatting you desire.

    Note 2: Although the above examples are laid out on separate lines, that is for presentation purposes only; your mailmerge main document would have the fields all on the same logical line.

    Note 3: Where a mergefield outputs only numeric data, it may be possible to use numeric picture switches to control the colouring. This is described in my Microsoft Word Field Maths Tutorial, available in the ‘Sticky’ thread at the top of the Word forum:
    http://www.msofficeforums.com/word/38720-microsoft-word-field-maths-tutorial.html

    Note 4: You can’t use * Charformat switches with numeric picture switches or date switches. A workaround would be to enclose the field with the The * Charformat switch doesn’t work on systems with Office set up for use with a RTL keyboard – even if that keyboard is not enabled. A workaround would be to apply the desired formatting to the entire field (preferably via a Character Style).

    Conditionally Shade Table Cells
    Word doesn’t have a conditional shading function like Excel has, but you can achieve a similar result in a mailmerge via field coding. To do this, you need a set of fields (one for each condition) in the relevant cell(s), along the lines of:

    {IF{MERGEFIELD Condition}= “1” “→→↵
    →Condition 1 Text→↵
    →→” * Charformat}
    {IF{MERGEFIELD Condition}= “2” “→→↵
    →Condition 2 Text→↵
    →→” * Charformat}
    {IF{MERGEFIELD Condition}= “3” “→→↵
    →Condition 3 Text→↵
    →→” * Charformat}
    {IF{MERGEFIELD Condition}= “4” “→→↵
    →Condition 4 Text→↵
    →→” * Charformat}
    {IF{MERGEFIELD Condition}= “5” “→→↵
    →Condition 5 Text→↵
    →→” * Charformat}

    where the ‘I’ in each ‘IF’ is highlighted with the relevant highlight colour and each cell to be shaded has:
    • margins set to 0 all round
    • paragraph formatting with a single right-aligned tab-stop set to at least the cell width.

    Note: All the fields depicted above should be inserted one after the other, without line/paragraph breaks between them – the above separations are just to make the field coding easier to follow.

    In the above depiction, five conditions are provided for, but you can have more or less – highlighting allows 16 possibilities and font colouring can be used to expand the colour differentiations even further.

    Catalog/Directory Mailmerge to Label Stationery
    To use a catalog mailmerge with label stationery, all you need to do is to set up the page layout in the mailmerge main document so that you’ve got the same column layout and margins as the labels, then put the mergefields inside a single-cell table of the correct dimensions for a single label.

    Suppress Output on Unused Labels in a Label Merge
    Ordinarily, any default text intended for printing on labels will appear on all labels on the last page of a label merge, even after the last record has been output. To prevent that, you can use an IF test that looks at the MERGEREC field’s value. For example:

    {IF{MERGEREC} “” “Text to Display”}

    This can be use with the conditional display of other mergefields in conjunction with the default text. For example:

    {IF{MERGEREC} “” “Default Text: {IF«MyField»= “” “No Record” «MyField»}”}
    or:
    {IF{MERGEREC} “” “Default Text: {IF{MERGEFIELD MyField}= “” “No Record” {MERGEFIELD MyField}}”}

    Send Mailmerge Output to Individual Files
    By adding the following macro to your mailmerge main document, you can generate one output file per record. Files are saved to the same folder as the mailmerge main document, using the ‘Last_Name’ & ‘First_Name’ fields in the data source for the filenames (change these to suit your requirements). PDF & DOCX formats are catered for.
    [Code]Sub Merge_To_Individual_Files()
    ‘Merges one record at a time to the folder containing the mailmerge main document.
    ‘ Sourced from: /showthread//163017-Word-Mailmerge-Tips-amp-Tricks
    Application.ScreenUpdating = False
    Dim StrFolder As String, StrName As String, MainDoc As Document, i As Long, j As Long
    Const StrNoChr As String = “””*./:?|”
    Set MainDoc = ActiveDocument
    With MainDoc
    StrFolder = .Path & Application.PathSeparator
    For i = 1 To .MailMerge.DataSource.RecordCount
    With .MailMerge
    .Destination = wdSendToNewDocument
    .SuppressBlankLines = True
    With .DataSource
    .FirstRecord = i
    .LastRecord = i
    .ActiveRecord = i
    If Trim(.DataFields(“Last_Name”)) = “” Then Exit For
    ‘StrFolder = .DataFields(“Folder”) & Application.PathSeparator
    StrName = .DataFields(“Last_Name”) & “_” & .DataFields(“First_Name”)
    End With
    .Execute Pause:=False
    If Err.Number = 5631 Then
    Err.Clear
    GoTo NextRecord
    End If
    End With
    For j = 1 To Len(StrNoChr)
    StrName = Replace(StrName, Mid(StrNoChr, j, 1), “_”)
    Next
    StrName = Trim(StrName)
    With ActiveDocument
    .SaveAs FileName:=StrFolder & StrName & “.docx”, FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
    ‘ and/or:
    .SaveAs FileName:=StrFolder & StrName & “.pdf”, FileFormat:=wdFormatPDF, AddToRecentFiles:=False
    .Close SaveChanges:=False
    End With
    NextRecord:
    Next i
    End With
    Application.ScreenUpdating = True
    End Sub[/Code]
    Note 1: The above code defaults to saving the output to the mailmerge main document’s folder. You can change the destination folder by editing:
    StrFolder = .Path & Application.PathSeparator
    If destination folders are specified in the data source, you could delete or comment-out that line and un-comment the line:
    ‘StrFolder = .DataFields(“Folder”) & Application.PathSeparator
    where the folder the output is to be saved to is in a data field named ‘Folder’. Alternatively, to save the output to the same folder as the data source, you could replace:
    StrFolder = .Path & Application.PathSeparator
    with:
    StrFolder = .MailMerge.DataSource.Name
    i = InStrRev(StrFolder, Application.PathSeparator)
    StrFolder = Left(StrFolder, i)

    Illegal filename characters (i.e. “*./:?|) are replaced with underscores.

    Note 2: If you’re using Word 2007 or later, your mailmerge main document will need to be saved in the .doc or .docm formats, as documents using the .docx format cannot contain macros.

    Note 3: If you rename the above macro as ‘MailMergeToDoc’, clicking on the ‘Edit Individual Documents’ button will intercept the merge and the process will run automatically. The potential disadvantage of intercepting the ‘Edit Individual Documents’ process this way is that you no longer get to choose which records to merge at that stage. However, you can still achieve the same outcome – and with greater control – via the ‘Edit Recipient List’ tools.

    Run a Mailmerge from Excel, Sending the Output to Individual Files
    The following macro automates a mailmerge from Excel. The code assumes you have a document named ‘MailMergeMainDocument.docx’ stored in the same folder as the Excel workbook. That document should be saved as an ordinary, macro-free, document, not as a mailmerge main document. As coded, the macro also assumes a standard query, processing all records from Sheet1. Change the sheet references, as appropriate. If you’re using filtering, you’d have to add that to the macro’s SQLStatement, too. Each record’s output is sent to a new file in the same folder as the Excel workbook, using the ‘Last_Name’ & ‘First_Name’ fields in the data source for the filenames (change these to suit your requirements). PDF & DOCX save formats are catered for. Illegal filename characters (i.e. “*./:?|) are replaced with underscores.
    [Code]Sub RunMerge()
    ‘Merges one record at a time to the folder containing the Excel workbook.
    ‘ Sourced from: /showthread//163017-Word-Mailmerge-Tips-amp-Tricks
    ‘Note: this code requires a reference to the Word object model to be set, via Tools|References in the VBE.
    Application.ScreenUpdating = False
    Dim StrMMSrc As String, StrMMDoc As String, StrMMPath As String, StrName As String
    Dim i As Long, j As Long
    Const StrNoChr As String = “””*./:?|”
    Dim wdApp As New Word.Application, wdDoc As Word.Document
    wdApp.Visible = False
    wdApp.DisplayAlerts = wdAlertsNone
    StrMMSrc = ThisWorkbook.FullName
    StrMMPath = ThisWorkbook.Path & “”
    StrMMDoc = StrMMPath & “MailMergeMainDocument.doc”
    Set wdDoc = wdApp.Documents.Open(Filename:=StrMMDoc, AddToRecentFiles:=False, ReadOnly:=True, Visible:=False)
    With wdDoc
    With .MailMerge
    .MainDocumentType = wdFormLetters
    .OpenDataSource Name:=StrMMSrc, ReadOnly:=True, AddToRecentFiles:=False, _
    LinkToSource:=False, Connection:=”Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;” & _
    “Data Source=StrMMSrc;Mode=Read;Extended Properties=””HDR=YES;IMEX=1″”;”, _
    SQLStatement:=”SELECT * FROM `Sheet1$`”
    For i = 1 To .DataSource.RecordCount
    .Destination = wdSendToNewDocument
    .SuppressBlankLines = True
    With .DataSource
    .FirstRecord = i
    .LastRecord = i
    .ActiveRecord = i
    If Trim(.DataFields(“LAST_NAME”)) = “” Then Exit For
    StrName = .DataFields(“LAST_NAME”) & “_” & .DataFields(“FIRST_NAME”)
    End With
    .Execute Pause:=False
    For j = 1 To Len(StrNoChr)
    StrName = Replace(StrName, Mid(StrNoChr, j, 1), “_”)
    Next
    StrName = Trim(StrName)
    With wdApp.ActiveDocument
    .SaveAs Filename:=StrMMPath & StrName & “.docx”, FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
    ‘ and/or:
    ‘.SaveAs Filename:=StrMMPath & StrName & “.pdf”, FileFormat:=wdFormatPDF, AddToRecentFiles:=False
    .Close SaveChanges:=False
    End With
    Next i
    .MainDocumentType = wdNotAMergeDocument
    End With
    .Close SaveChanges:=False
    End With
    wdApp.DisplayAlerts = wdAlertsAll
    wdApp.Quit
    Set wdDoc = Nothing: Set wdApp = Nothing
    Application.ScreenUpdating = False
    End Sub[/Code]
    Note 1: The above code requires a reference to the Word object model to be set, via Tools|References in the VBE.

    Note 2: For testing purposes, you might want to change the line ‘wdApp.Visible = False’ to ‘wdApp.Visible = True’.

    If you already have a mailmerge main document set up with (or without) filtering, you could use the following Word macro to retrieve the SQL statement:
    [Code]Sub GetSQL()
    With ActiveDocument.MailMerge
    If .MainDocumentType wdNotAMergeDocument Then
    MsgBox “Mail Merge Query String:” & vbCr & .DataSource.QueryString
    Else
    MsgBox “Not A Merge Document”
    End If
    End With
    End Sub[/Code]

    Split Merged Output to Separate Documents
    Execute the merge to a new document and then run the following macro over that document.
    [Code]Sub SplitMergedDocument()
    ‘ Sourced from: /showthread//163017-Word-Mailmerge-Tips-amp-Tricks
    Application.ScreenUpdating = False
    Dim i As Long, j As Long, k As Long, StrTxt As String
    Dim Rng As Range, Doc As Document, HdFt As HeaderFooter
    Const StrNoChr As String = “””*./:?|”
    j = InputBox(“How many Section breaks are there per record?”, “Split By Sections”, 1)
    With ActiveDocument
    ‘ Process each Section
    For i = 1 To .Sections.Count – 1 Step j
    With .Sections(i)
    ‘*****
    ‘ Get the 1st paragraph
    Set Rng = .Range.Paragraphs(1).Range
    With Rng
    ‘ Contract the range to exclude the final paragraph break
    .MoveEnd wdCharacter, -1
    StrTxt = .Text
    For k = 1 To Len(StrNoChr)
    StrTxt = Replace(StrTxt, Mid(StrNoChr, k, 1), “_”)
    Next
    End With
    ‘ Construct the destination file path & name
    StrTxt = ActiveDocument.Path & Application.PathSeparator & StrTxt
    ‘*****
    ‘ Get the whole Section
    Set Rng = .Range
    With Rng
    If j > 1 Then .MoveEnd wdSection, j – 1
    ‘Contract the range to exclude the Section break
    .MoveEnd wdCharacter, -1
    ‘ Copy the range
    .Copy
    End With
    End With
    ‘ Create the output document
    Set Doc = Documents.Add(Template:=ActiveDocument.AttachedTemplate.FullName, Visible:=False)
    With Doc
    ‘ Paste contents into the output document, preserving the formatting
    .Range.PasteAndFormat (wdFormatOriginalFormatting)
    ‘ Delete trailing paragraph breaks & page breaks at the end
    While .Characters.Last.Previous = vbCr Or .Characters.Last.Previous = Chr(12)
    .Characters.Last.Previous = vbNullString
    Wend
    ‘ Replicate the headers & footers
    For Each HdFt In Rng.Sections(j).Headers
    .Sections(j).Headers(HdFt.Index).Range.FormattedText = HdFt.Range.FormattedText
    Next
    For Each HdFt In Rng.Sections(j).Footers
    .Sections(j).Footers(HdFt.Index).Range.FormattedText = HdFt.Range.FormattedText
    Next
    ‘ Save & close the output document
    .SaveAs FileName:=StrTxt & “.docx”, FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
    ‘ and/or:
    .SaveAs FileName:=StrTxt & “.pdf”, FileFormat:=wdFormatPDF, AddToRecentFiles:=False
    .Close SaveChanges:=False
    End With
    Next
    End With
    Set Rng = Nothing: Set Doc = Nothing
    Application.ScreenUpdating = True
    End Sub[/Code]

    Illegal filename characters (i.e. “*./:?|) are replaced with underscores.

    As coded, it is assumed the output filename consists of the first paragraph in each record. If not, you could use a different range or replace all of the content between the ***** strings with code like
    [Code] ‘ Construct the destination file path & name
    StrTxt = ActiveDocument.Path & Application.PathSeparator & (i + j – 1) / j[/Code]

    Convert Text Representations of Fields to Working Fields
    The following macro converts text representations of Word field codes to working field codes.
    [Code]Sub FieldStringToCode()
    ‘ Converts “textual” field codes into real field codes. To do the conversion, simply paste the “textual”
    ‘ field codes into your document, select them and run the macro.
    ‘ Sourced from: /showthread//163017-Word-Mailmerge-Tips-amp-Tricks
    Dim RngFld As Range, RngTmp As Range, oFld As Field
    Dim bFldCodes As Boolean, StrTmp As String, TrkStatus As Boolean
    Const Msg1 = “Select the text to convert and try again.”
    Const Msg2 = “There are no field strings in the selected range.”
    Const Msg3 = “Unmatched field brace pairs in the selected range.”
    Const Title1 = “Error!”
    bFldCodes = ActiveDocument.ActiveWindow.View.ShowFieldCodes
    If Selection.Type wdSelectionNormal Then
    MsgBox Msg1, vbExclamation + vbOKOnly, Title1
    Exit Sub
    End If
    If InStr(1, Selection.Text, “{“) = 0 Or _
    InStr(1, Selection.Text, “}”) = 0 Then
    MsgBox Msg2, vbCritical + vbOKOnly, Title1
    End If
    If (Len(Replace(Selection.Text, “{“, vbNullString)) _
    Len(Replace(Selection.Text, “}”, vbNullString))) Or _
    (Len(Replace(Selection.Text, “«”, vbNullString)) _
    Len(Replace(Selection.Text, “»”, vbNullString))) Then
    MsgBox Msg3, vbCritical + vbOKOnly, Title1
    Exit Sub
    End If
    With ActiveDocument
    TrkStatus = .TrackRevisions
    .TrackRevisions = False
    End With
    Application.ScreenUpdating = False
    ActiveDocument.ActiveWindow.View.ShowFieldCodes = True
    Set RngFld = Selection.Range
    With RngFld
    .End = .End + 1
    With .Duplicate.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Format = False
    .Forward = True
    .Text = “»”
    .Replacement.Text = “}”
    .Execute Replace:=wdReplaceAll
    .Forward = False
    .Wrap = wdFindStop
    .Text = “«”
    .Replacement.Text = “{MERGEFIELD ”
    .Execute Replace:=wdReplaceAll
    End With
    Do While InStr(1, .Text, “{“) > 0
    Set RngTmp = ActiveDocument.Range(Start:=.Start + _
    InStr(.Text, “{“) – 1, _
    End:=.Start + InStr(.Text, “}”))
    With RngTmp
    Do While Len(Replace(.Text, “{“, vbNullString)) _
    Len(Replace(.Text, “}”, vbNullString))
    .End = .End + 1
    If .Characters.Last.Text “}” Then .MoveEndUntil cset:=”}”, _
    Count:=Len(ActiveDocument.Range(.End, RngFld.End))
    Loop
    .Characters.First = vbNullString
    .Characters.Last = vbNullString
    StrTmp = .Text
    Set oFld = ActiveDocument.Fields.Add(Range:=RngTmp, _
    Type:=wdFieldEmpty, Text:=””, PreserveFormatting:=False)
    oFld.Code.Text = StrTmp
    End With
    Loop
    ActiveDocument.ActiveWindow.View.ShowFieldCodes = bFldCodes
    .End = .End – 1
    If bFldCodes = False Then .Fields.ToggleShowCodes
    .Select
    End With
    Set RngTmp = Nothing: Set RngFld = Nothing: Set oFld = Nothing
    ActiveDocument.TrackRevisions = TrkStatus
    Application.ScreenUpdating = True
    End Sub[/code]

    Cheers,
    Paul Edstein
    [Fmr MS MVP - Word]

    2 users thanked author for this post.
    Viewing 0 reply threads
    Author
    Replies
    • #2316273

      Hi Woody,

      It seems like the mailmerge in Word for Office 365 is not accepting any IFs where the result of the MERGEFIELD is a numeric value.

      I get errors with conditions like these:

      {IF{MERGEFIELD Field1}>0 “Yes” “No”}    (when the field contains a numeric value)

      {IF{={IF{MERGEFIELD Field1}= “True Text” 1 0}+{IF{MERGEFIELD Field2}= “True Text” 1 0}+{IF{MERGEFIELD Field3}= “True Text” 1 0}+{IF{MERGEFIELD Field4}= “True Text” 1 0}}> 0 “At least one condition not met” “No conditions met”}

      Do you know how to solve this? I need it urgently.

      Best regards,

      Thierry

    Viewing 0 reply threads
    Reply To: Word Mailmerge Tips & Tricks

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: