I'm trying to pull data from an Excel sheet using an ADO query. However, date values are being returned the way they're formatted on the worksheet, rather than the actual date value. For example, the value 8/12/1929
is formatted as 8/12/29
, so the query is returning the string "8/12/29". This makes it hard to determine what the correct date is based on the recordset data alone, as the year could also be 2029 in this case.
Here's the code for the ADO query:
Function WorksheetRecordset(workbookPath As String, sheetName As String) As ADODB.Recordset
Dim objconnection As New ADODB.Connection
Dim objrecordset As New ADODB.Recordset
'On Error GoTo errHandler
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
objconnection.CommandTimeout = 99999999
objconnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & workbookPath & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"";"
objrecordset.Open "Select * FROM [" & sheetName & "$]", _
objconnection, adOpenStatic, adLockOptimistic, adCmdText
If objrecordset.EOF Then
Set WorksheetRecordset = Nothing
Exit Function
End If
Set WorksheetRecordset = objrecordset
On Error GoTo 0
Exit Function
errHandler:
Set WorksheetRecordset = Nothing
On Error GoTo 0
End Function
I'm fetching the value by using, e.g.
Sub getValue(rs as ADODB.Recordset)
Debug.Print rs.Fields(0).Value
End Sub
Part of the problem might be that the date values don't start until after several rows of text, so maybe when ADO detects the field type as text it only fetches the visible formatted value. Is there a way to retrieve the actual date value?
EDIT: Just realized that this is similar to this SO question that I previously asked: ADO is truncating Excel data. But I didn't get a satisfactory answer from that one, so I'll ask this one anyways.