I have a VB.NET project wherein I am trying to merge an Excel document with Word documents (containing the merge fields). The code works well (in slightly modified forms) for the same process in other parts of my code, but this one doesn't work at all. The RecordCount keeps returning -1 which would seem to indicate a problem with the merge. Here is the code I have so far up to the point where it breaks:
Dim wdECASuitApp As New Word.Application
Dim wdECASuitDoc As New Word.Document
Dim Records As Integer
wdECASuitDoc = wdECASuitApp.Documents.Open("X:\My Template.doc")
wdECASuitApp.Visible = False 'Set this to False before going live -- true for debugging
wdECASuitDoc.MailMerge.OpenDataSource(Name:=SourceFile, SQLStatement:="SELECT * FROM [Sheet1$] WHERE [Client Short] = 'ABC'")
After the last line of code above runs, wdECASuitDoc.MailMerge.DataSource.RecordCount
returns -1 and my mail program skips this section since there were no records.
I mainly work in SQL Server, so I know my SQL statement syntax is correct if this were a SQL Server query, however I don't know of any specific conventions for using SQL in this context.
The other merges performed in the same program work great however their SQL Statements do not include any single quotes. I'm wondering if the single quotes need to be escaped somehow.
The problem is with the OpenDataSource
in the last line in the code block above. Maybe someone here can see what I am missing....
Thanks in advance!
EDIT: I have confirmed there are records in the datasource that meet the criteria in the SQL Statement, so I know it's not simply a matter of records not existing. The -1 return value leads me to believe it is an error with the query or OpenDataSource statement.