Excel中日期值的ADO查询返回工作表中格式的字符串



我正试图使用ADO查询从Excel工作表中提取数据。但是,返回的日期值是工作表中的格式,而不是实际的日期值。例如,值8/12/1929的格式为8/12/29,因此查询返回字符串"8/12/29"。这使得仅根据记录集数据很难确定正确的日期,因为在这种情况下,年份也可能是2029年。

以下是ADO查询的代码:

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

我通过使用例如来获取值

Sub getValue(rs as ADODB.Recordset)
Debug.Print rs.Fields(0).Value
End Sub

部分问题可能是日期值直到几行文本之后才开始,所以当ADO检测到字段类型为文本时,它可能只获取可见的格式化值。是否有检索实际日期值的方法?

编辑:刚刚意识到这与我之前问的这个问题类似:ADO正在截断Excel数据。但我并没有从那个人那里得到一个满意的答案,所以我无论如何都会问这个。

由于您有58个字段,我认为最好的方法是在包含数据的工作簿上构建一个运行以下代码的字符串:

Dim rng as Range
Dim val as Variant, txt as String
Set rng = Worksheets("sheetName").Range("A3:BF3")
For Each val In rng.Value
txt = txt & "[" & val & "], "
Next val
Debug.Print txt

然后你从即时窗口复制文本并粘贴到你的代码中,如下所示:

Dim strFields as String, strSQL as String
strFields = 'Paste the text here
'Note the FROM clause modification 
strSQL = "SELECT CDATE([myDate]), " & strFields & " FROM [" & sheetName & "$A3:BF]"
'...
objrecordset.Open strSQL, _
objconnection, adOpenStatic, adLockOptimistic, adCmdText

请注意,FROM子句的形式为[sheet$A3:BF]。这将第三行指定为包含数据的第一行。这个问题或这个链接中的更多细节

最新更新