VBA DAO.OpenRecordSet 不一致错误

VBA DAO.OpenRecordSet Inconsistent Errors

运行 访问 2016

我正在尝试从 Excel 的 MS Access .mdb table 导入数据。 (我的客户端使用的专有软件只能识别 *.mdb 文件。)当我 运行 此代码时 table 关闭时,我得到错误:

Run-Time Error 3061
Too few parameters - Expected 2

如果我 运行 在 Access 中打开 table 时的代码,有一半的时间我会收到该错误,而有一半的时间我会收到:

Run-Time error '3008'
The table 'Daily_Logs_of_Flows' is already opened exclusively by 
another user, or it is already open through the user interface 
and cannot be manipulated programmatically.

这似乎表明 VBA 有时会越过第一个错误。

由于 this post on Whosebug,我已经检查了变量名称,并且在 monthToImport 之前和之后都使用了单引号和数字符号 (#)。错误来自

Expected 3 

Expected 2

这是代码

Sub importPLCDataFromAccess(monthToImport As Date)

Dim myDbLocation As String
myDbLocation = "K:\Users\WWTP Computer\Documents\POV_Projects\PLC Interface\PLC_Data.mdb"

DIM mySQLCall as String

Set myWorkbook = ActiveWorkbook
Set myDataSheet = myWorkbook.Worksheets("Page 1")

Set myEngine = New DAO.DBEngine
'Set myWorkspace = myEngine.Workspaces(0)
Set myDB = myEngine.OpenDatabase(myDbLocation)
' I deleted the workspace
' Set myDB = myWorkspace.OpenDatabase(myDbLocation)

mySQLCall = "SELECT Time_Stamp, GolfVolume, CreekVolume, InfluentVolume FROM Daily_Logs_of_Flows "
' Limit records to month requested...
mySQLCall = mySQLCall & "WHERE (DATEPART(m,Time_Stamp) = DATEPART(m,#" & monthToImport & "#)) "
'  ... during the year requested
mySQLCall = mySQLCall & "AND (DATEPART(yyyy,Time_Stamp) = DATEPART(yyyy,#" & monthToImport & "#)) "
mySQLCall = mySQLCall & "ORDER BY Time_Stamp"

Debug.Print "mySQLCall = " & mySQLCall
Debug.Print "monthToImport: " & monthToImport

'Error occurs on next line where execute query & populate the recordset

Set myRecordSet = myDB.OpenRecordset(mySQLCall, dbOpenSnapshot)

'Copy recordset to spreadsheet
Application.StatusBar = "Writing to spreadsheet..."
Debug.Print "RecordSet Count = " & myRecordSet.recordCount

If myRecordSet.recordCount = 0 Then
    MsgBox "No data retrieved from database", vbInformation + vbOKOnly, "No Data"
    GoTo SubExit
End If
'....
End Sub  

这是 SQL 声明的 Debug.Print 当前内容:

mySQLCall = SELECT Time_Stamp, GolfVolume, CreekVolume, InfluentVolume FROM Daily_Logs_of_Flows WHERE (DATEPART(m,Time_Stamp) = DATEPART(m,#6/1/2016#)) AND (DATEPART(yyyy,Time_Stamp) = DATEPART(yyyy,#6/1/2016#)) ORDER BY Time_Stamp

对我在这里缺少的东西有什么想法吗?预先感谢您的帮助。

问题是 DATEPART 函数需要引号中的第一个参数,否则它会查找字段 yyyym.

例如:

DATEPART("yyyy", #6/1/2016#)

DATEPART("m", #6/1/2016#)

总计:

SELECT Time_Stamp, GolfVolume, CreekVolume, InfluentVolume _
FROM Daily_Logs_of_Flows 
WHERE (DATEPART("m",Time_Stamp) = DATEPART("m",#6/1/2016#)) 
      AND (DATEPART("yyyy",Time_Stamp) = DATEPART("yyyy",#6/1/2016#)) 
ORDER BY Time_Stamp

要在 VBA 中执行此操作(以防万一您不知道,但我猜您知道),只需在每次调用 DATEPART 函数时将引号加倍即可。 ..

例如:

mySQLCall = mySQLCall & "AND (DATEPART(""yyyy"",Time_Stamp)...."

为了完整起见,运行-时间错误“3008”实际上是第一个错误....Access 不会尝试 运行 任何 SQL 直到它可以确定它具有适当的权限。