I am importing data into Excel from a SQL Server 2012 database. The issue I have is that SQL Server 2012 Date datatype columns are not being recognised consistently in Excel.
If I use ADO Recordsets to import data from specific columns, data with column datatype Date or Datetime is copied into the Recordset as VBA datatype String (instead of Date or Integer).
Reproducing the Recordset in Excel yields strings in the format yyyy-mm-dd. These cells are not recognized by Excel as date/time, even if I change the formatting.
Yet when I refer to the Excel cell from another cell the Date type is recognized (eg: A1 contains the result of my SQL VBA Recordset query, for example "2013-04-17". I enter into cell A2 "=A1 + 1", A2 will display it as 41382.
However, when I use MS Query to extract data from the same Database using ListObjects and ODBC, the same data from the same database is returned with dates being interpreted correctly by Excel (ie I import a column called "Transaction Date" with SQL datatype Datetime via MS Query the result will be a MS Excel Date "Integer").
How do I amend my VBA Recordset code to treat data in the format yyyy-mm-dd as dates instead of strings?
Thanks, John
PS: SQL queries I execute vary so that sometimes I get data from columns with datatype "date" and sometimes its just integers or Double datatype. This means that hardcording "Convert(INT, TransactionDate)" into the SELECT statement is not really possible. However, I am a total amateur at SQL so there might be a super easy solution to this (eg if I ever access columns with datatype "DateTime" then SQL should always send "CONVERT(DBL, XXX)" instead of XXX where XXX is a column with datatype DATE.
Function GetSQL(strQuery As String) As Variant
Dim rst As ADODB.Recordset
Dim element As Variant
Dim i, j As Integer
Dim v As Variant
On Error GoTo aError
Call ConnecttoDB
cnt.Open
Set rst = New ADODB.Recordset
rst.Open strQuery, cnt, adOpenStatic
rst.MoveFirst
If rst.RecordCount = 0 Then 'i.e. if it's empty
v = CVErr(xlErrNA)
rst.Close
cnt.Close
Else
End If
v = rst.GetRows
For i = 0 To UBound(v, 1)
For j = 0 To UBound(v, 2)
If v(i, j) = -9999 Then
v(i, j) = CVErr(xlErrNA)
Else
End If
Next j
Next i
GetSQL = Application.WorksheetFunction.Transpose(v)
rst.Close
cnt.Close
Exit Function
aError:
MsgBox Err.Description
rst.Close
cnt.Close
End Function