为什么在Access中返回835条记录的查询会在VBA代码中返回空记录集?

时间:2013-10-01 18:13:21

标签: vba adodb recordset

以下代码稍微修改了我用于几乎每个我工作的项目(在Access中)的样板文件。此代码的所有其他版本在此数据库中完美运行。这些表实际上都在SQL Server中,但它们在此Access数据库中链接。

这是奇怪的部分...当我运行代码并进入“使用rs”并执行“.Open”时,下一步“Do While Not .EOF”跳到“Do”的底部“......我在.EOF!但是,如果我获得“.Source”SQL语句的副本并将其粘贴到非代码Access主窗口上的空白SQL查询中,我将从该查询中获取835条记录。如果此查询应返回835条记录,我怎么能找回空记录集?

我尝试更改我的.CursorType和.LockType,但无济于事。

任何人都有任何关于我可以尝试对此进行排查的想法吗?

Public Sub test()
Dim db As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sFromDate As String
Dim sToDate As String
Dim sSubUnit As String

sFromDate = "1/1/2013"
sToDate = "1/31/2013"
sSubUnit = "2???"

' Make a connection to the db
Set db = CurrentProject.Connection

With rs
    .ActiveConnection = db
    .CursorType = adOpenForwardOnly
    .LockType = adLockReadOnly

    .Source = "SELECT SCEVENT.CLIENT_ID, SCATTEND.EMP_ID, SCATTEND.STARTDATE, SCATTEND.SVC_ID " & _
                "FROM SCATTEND LEFT JOIN SCEVENT ON SCATTEND.SCEVENT_ID = SCEVENT.ID " & _
                "WHERE (SCATTEND.STARTDATE Between #" & sFromDate & "# And #" & sToDate & "#) " & _
                    "AND (SCATTEND.SUBUNIT_ID Like '" & sSubUnit & "') " & _
                    "AND ((APPTYP_ID IS NULL) OR (APPTYP_ID IN (1,2))) " & _
                "ORDER BY SCEVENT.CLIENT_ID, SCATTEND.EMP_ID, SCATTEND.STARTDATE, SCATTEND.SVC_ID;"
    .Open
    Do While Not .EOF
        MsgBox "there are records!"
        .MoveNext
    Loop
    .Close
End With

Set rs = Nothing
Set db = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

它可能与ADO和DAO

之间的区别有关

Difference between ADO and DAO