Excel中date值的ADO查询返回格式在工作表中的string

我试图使用ADO查询从Excel工作表中提取数据。 但是,date值将以在工作表上格式化的方式返回,而不是实际的date值。 例如,值8/12/1929被格式化为8/12/29 ,因此查询返回string“8/12/29”。 这使得很难确定什么是正确的date是基于单独的logging集数据,因为在这种情况下,年份也可以是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 

部分问题可能是date值直到几行文本之后才开始,所以也许ADO检测到字段types为文本时,它只会获取可见的格式化值。 有没有办法检索实际的date值?

编辑:只是意识到这是类似于这个问题,我以前问: ADO截断Excel数据 。 但是我没有得到一个满意的答案,所以我会问这个问题。

既然你有58个字段,我认为最好的办法是在包含数据的工作簿上build立一个运行以下代码的string:

 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] 。 这将第三行指定为包含数据的第一行。 在这个问题或在这个链接的更多细节