I have an Excel worksheet that is connected to an Oracle database via ODBC which brings in invoice data. I am then attempting to read the data in the Excel worksheet from another worksheet in the same workbook by using a SQL statement using an excel range that defines the downloaded (linked) data.
The SQL statement works fine without the WHERE clause. When I add the WHERE clause which is setting criteria on a Date field, I get the error listed in the subject of this post. I believe the syntax I am using in the SQL statement for the date field is correct -- because if I copy the downloaded data and paste it as Values into another worksheet, and then process the SQL statement against this copied data, the SQL statement works. Also if I select other (non-date) fields to use in the WHERE clause, the code works.
Below is the code. (The range name "InvoiceData" defines the dataset that the SQL statement will read). Please let me know if you have any ideas how to correct. My backup plan is to simply copy / paste the data as values - but this will make the file considerably larger.
The error message of "the connection for viewing your linked Microsoft Excel ... was lost" is encountered on the last statement of the code.
Function OpenRangeRS(rng As Range) As Recordset
'**Returns as recordset for the passed in range or range name
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sDBPath As String
Dim sRangeAddress As String
Dim sFile As String
Dim sConnect As String
Dim sSQL As String
Dim dReportDate As Date
sDBPath = ThisWorkbook.FullName
sConnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & sDBPath & ";HDR=Yes';"
cn.Open sConnect
dReportDate = Range("SelectedDate")
sSQL = "SELECT * FROM [InvoiceData] "
sSQL = sSQL & " WHERE Invoice_Date = " & "#" & dReportDate & "#"
rs.Open sSQL, sConnect