views:

1709

answers:

3

Hey all

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.

A: 

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?

Dennis Palmer
i'm trying to take an excel spreadsheet and perform a mail merge with a Word template
A: 

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

TGnat
Word's mail merge has native support for reading Excel files, so why the extra step of the 3rd party control?
Dennis Palmer
It runs as an automated process, that matches client templates to the clients data. We do a few hundred of these a day.
TGnat
+3  A: 

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.

pgfearo