Question

I was wondering if anybody knew how to do a mail merge using an Excel file as a datasource, to fill in fields on a Word template? I wish to use the interop for Word if i could...but am having a few difficulties finding code for this. Does anybody have any syntax for this? Thank you in advance.

Was it helpful?

Solution

A very useful method for learning how to automate specific actions in MS Word is to actually perform the action manually with 'Record Macro' enabled.

Once you have the VBA macro its easy enough to convert this to VB.NET or C# that uses interop. I tend to tweak the VBA first manually in Word so I can then test this first before converting to a .NET language using the interop layer.

I don't know much about mailmerge, but this is some of the VBA generated whilst I recorded a macro:

ActiveDocument.MailMerge.MainDocumentType = wdFormLetters
ActiveDocument.MailMerge.OpenDataSource Name:= _
    "c:\Arrays.xlsx", ConfirmConversions:=False, _
     ReadOnly:=False, LinkToSource:=True, AddToRecentFiles:=False, _
    PasswordDocument:="", PasswordTemplate:="", WritePasswordDocument:="", _
    WritePasswordTemplate:="", Revert:=False, Format:=wdOpenFormatAuto, _
    Connection:= _
    "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=c:\Arrays.xlsx;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Type=37;Jet OLEDB:Database Loc" _
    , SQLStatement:="SELECT * FROM `Sheet1$`", SQLStatement1:="", SubType:= _
    wdMergeSubTypeAccess

I haven't included the full code here, but hopefully this give you some ideas.

OTHER TIPS

Word (at least in the 2007 version, which is what I'm looking at) can do this out of the box. Just select the Excel file as the datasource. What are you trying to do in your code?

I use this 3rd party control. You can read your xls file into a data table and then tell the control to merge it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top