我尝试连接到一个excel数据库(我知道它不是完美的数据库但我不能使用访问但我必须使用excel所以......) 一切正常,直到行:objRecordset.Open
我收到错误,我承认我不知道如何解决它
这是代码
Sub macromacro()
'On Error Resume Next
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
'***** Creation de la connection *****
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & ThisWorkbook.Path & "\StatsLyon.xlsm;" _
& "Extended Properties=""Excel 8.0;HDR=Yes;"";"
'***** Requête SQL *****
objRecordset.Open
Query = "Select SUM(NbCompteurElec) AS NombreTotal FROM [Feuil1$] ," _
& "objConnection, adOpenStatic, adLockOptimistic, adCmdText"
Feuil5.Cells(1, 3).Value = "NombreTotal"
Feuil5.Cells(1, 4).Value = objRecordset.Fields(NombreTotal).Value
objConnection.Close
Set objConnection = Nothing
End Sub
答案 0 :(得分:0)
你需要使用ACE * .xlsm& * .XLSX:
objConnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=" & ThisWorkbook.Path & "\StatsLyon.xlsm;" _
& "Extended Properties=""Excel 8.0;HDR=Yes;"";"
您可能还想使用
Extended Properties="Excel 12.0 Xml;HDR=YES";
有关详细信息,请参阅http://www.connectionstrings.com/excel-2007。
然后:
objRecordset.Open "Select SUM(NbCompteurElec) AS NombreTotal FROM [Feuil1$]", _
objConnection, adOpenStatic, adLockOptimistic
编辑重新评论
sSQL = "Select SUM(NbCompteurElec) AS NombreTotal FROM [Feuil1$] " _
& "WHERE [DateMad] Between #" _
& Format(date_deb,"yyyy/mm/dd") _
& "# And #" & Format(date_fin,"yyyy/mm/dd") & "#"
objRecordset.Open sSQL, objConnection, adOpenStatic, adLockOptimistic
日期的分隔符是#
最好将日期格式化为年份(yyyy),月份,日期,因为它从不含糊不清。