Search code examples
macosmergems-wordapplescriptmergefield

Refer to a Word for Mac merge field in an applescript


tell application "Microsoft Word"
 set theDoc to active document
 set theRecipient to "[email protected]"
 set theSubject to "Merged document"
 set theBody to "Please find the merged document attached."
 tell application "Microsoft Outlook"
  set newMessage to make new outgoing message with properties {subject:theSubject, content:theBody}
  tell newMessage
   make new recipient with properties {email address:{address:theRecipient}}
   open -- Display the email for review
  end tell
 end tell
end tell

This applescript runs perfectly.

The problem is that I need to use a Mac Word mergefield named "email" instead of hard coding the email address

I have tried

 set theRecipient to mergefield:email
 set theRecipient to {mergefield:email}
 set theRecipient to mergefield:"email"
 set theRecipient to {mergefield:"email"}

I cannot find the correct syntax to refer to a mergefield named "email" in the current word document.

In every case I get a 'variable not recognized' or similar error


Solution

  • Let's assume for the moment that the active document is your Mail Merge Main Document and it is attached to your data source.

    Then you can reference the value of a field called "email" in the active record in the Mail Merge Data Source using this

    set theRecipient to the data merge data field value of data merge data field "email" of the data source of the data merge of theDoc
    

    Since it's not obvious how to interpret that, you could break it down, e.g.

    set theDM to the data merge of theDoc
    set theDS to the data source of theDM
    set theDF to data merge data field "email" of theDS
    set theRecipient to the data merge data field value of theDF
    

    NB, Word field codes are mostly case-insensitive, but these data merge data names are not, i.e. if the name in the data source is actually "Email" then you need

    set theDF to data merge data field "Email" of theDS
    

    It looks to me as you are not actually using mail merge to perform your merge. If so, you will need some code to step through the records in the data source, because you cannot access any data source record other than the "active record" using the data merge/data source objects.

    If you were actually doing a mail merge, I think you would need to do this once, at the beginning of the merge

        set the mail address field name of the data merge of theDoc to "email"
    

    (In Windows Word Mail Merge it is possible to change the name of the "mail address field" during the merge if necessary, using the Mail Merge Events, but AFAICR they are not available in Mac Word).