【发布时间】:2018-08-01 16:43:09
【问题描述】:
我正在使用下面的函数从另一个工作簿中提取数据。它适用于非日期列,但不适用于包含日期的列
工作表的样子
不是日期列时有效:
Debug.Print GetSheetSQL(workbookPath, "Select columna from [sheet$]")(1)("columna")
--> 返回“palim”
如果 a 是 日期列 则不起作用
Debug.Print GetSheetSQL(workbookPath, "Select columnb from [sheet$]")(1)("columnb")
--> 什么都不返回
Function GetSheetSQL(path As String, sqlStr As String) As Collection
'''''''''''''''''''''''''''''''''''''''
'Open ADOB Connection and query via sql
' Connection string is standard and
' taken from:
' https://www.connectionstrings.com/microsoft-jet-ole-db-4-0/standard-excel/
Dim objConnection As Object
Dim objRecordSet As Object
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & path & ";Extended Properties=""Excel 8.0;HDR=Yes"""
objRecordSet.Open sqlStr, objConnection, adOpenStatic, adLockOptimistic, adCmdText
'''''''''''''''''''''''''''''''''''''''
'Iterate through queried table
' table is a collection with a row per row in the table
' row is a dictionary with table headings as key, returning the corresponding value
Dim table As Collection
Set table = New Collection
Dim row As Object
Dim fld
'iterate through recordset rows
Do Until objRecordSet.EOF
With objRecordSet
Set row = CreateObject("Scripting.Dictionary")
For Each fld In .Fields
row.Add fld.Name, fld.Value
Next fld
table.Add row
.MoveNext
End With
Loop
Set GetSheetSQL = table
'Close Connection; reset Error Handling to default
objConnection.Close
On Error GoTo 0
Exit Function
ErrorCloseConn:
objConnection.Close
On Error GoTo 0
Resume
End Function
【问题讨论】:
-
我试过你的代码,它对我来说很好用。
Returns Nothing是什么意思? -
你的SQL语句少了几个引号 --
"Select ... [sheet$]" -
对不起,我在原始 stmt 中有这些。我会改变的
-
@Storax 它返回字符串“NULL”,尽管我确信该行中有某物,或者有时只是“”
-
我可以重现您的问题。您的日期字段之一是否可能实际上是文本。至少这是我能够重现该问题的方式。在这种情况下,ADODB 将忽略 excel 中单元格的内容。