VBA DAO.OpenRecordSet不一致的错误

时间:2016-07-12 23:16:31

标签: vba ms-access recordset

运行Access 2016

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

Run-Time Error 3061
Too few parameters - Expected 2

如果我在Access中打开表时运行代码,HALF时间,我得到错误并且有一半的时间:

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 StackOverflow,我检查了变量名并在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

对于我在这里缺少什么的想法?在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

问题是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,直到它可以确定它具有适当的权限。

相关问题