Question

I want to create a MS Word merge document. I have already created a template document. When my application is started, it creates an ODBC, called "Hrms2008". I am new to this kind of stuff, that's why I don't know what causes the error.

  word.Application wrdApp;
                word.Document wrdDoc;

                object oMissing = System.Reflection.Missing.Value;
                object oName = "DSN=Hrms2008;DATABASE=Pitshrms4002;Integrated Security = True;";
                object oSQL = "Select * from tiblMerge";
                object oTemplate = briefNieuw.Brief;

                wrdApp = new word.Application();
                wrdApp.Visible = true;

                wrdDoc = wrdApp.Documents.Add(ref oTemplate,ref oMissing,ref oMissing,ref oMissing);

                wrdDoc.MailMerge.MainDocumentType = word.WdMailMergeMainDocType.wdFormLetters;
                wrdDoc.MailMerge.OpenDataSource("", oName, oSQL);

The error I get: "Type mismatch. Exception from HRESULT: 0X80020005 (DISP_ETYPEMISMATCH)"

What am I doing wrong here?

Was it helpful?

Solution

OpenDataSource expects a lot more parameters, i.e. the Connection string is the 12th parameter and the SQL Statement parameter is the 13th. Since all the parameters are defined as "object" in C#, with a recent enough C#, the compiler should accept 3 parameters, but at runtime COM expects the 2nd parameter to be the Format, and so on. So the first thing you need to do is either use named parameters (if your version of C# supports that) or provide the missing parameters and get the connection and sqlstatement parameters in the right place.

Beyond that, if the connection string and SQL statement work OK outside Word, you will almost certainly encounter further problems in Word, e.g.

For an ODBC connection, certainly one with a Name set to "", Word typically expects you to set the value of the Subtype parameter to wdMergeSubtypeWord2000 (please check that name!).

Even though there is nothing wrong with the SQL you have, in some cases Word objects if you do not "quote" the table name, e.g. using Select * from "tiblMerge"

When using the ODBC driver via OpenDataSource, any columns with Unicode string datatypes (NVARCHAR, NCHAR etc.) will return blank/null.

Because of the problem with Unicode, as a general rule with Word it is currently better to try to use the OLE DB provider, despite the fact that Microsoft has announced that ODBC will be its future connection standard for SQL Server. To use OLE DB, the Name parameter needs to be suitable .odc file with all the relevant connection information, or it can specify an empty .odc file and you can provide connection info. in the Connection parameter.

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