错误设置 VBA 来自 ADODB.recordset 的表单记录集

Error setting VBA Recordset of form from ADODB.recordset

我在 MS Access 2010 中使用 VBA 创建了一个函数来执行 SQL 服务器存储过程和 ADODB.Recordset 对象中的 return 值。但是,我无法使用来自 ADODB 连接的 return 记录集设置 MS Access 表单 RecordSource 或 Recordset。

下面是代码摘录:

Dim objRs As ADODB.Recordset
Set objRs = call_proc("mySQLProc", "param")
Set Forms("form1").Recordset = objRs

call_proc的函数头:

Public Function call_proc(procName As String, procVal As String) As ADODB.Recordset

如果我遍历 objRS 并执行 Debug.Print 我能够看到所有记录。所以我知道数据在那里。只是不知道如何修复将数据绑定到表单的错误。 下面的代码行 returns error:

Set Forms("form1").Recordset = objRs

欢迎接受任何建议。 先感谢您。

已修复。问题出在我的 call_proc 函数中。当我打开 ADODB.Recordset 时,我没有设置光标位置。请参阅下面我添加 "' <---#####ADD THIS"

的代码
Public Function call_proc(procName As String, procVal As String) As ADODB.Recordset

    ' Initialize variables.
    Dim cn As New ADODB.Connection
    Dim objCmd As New ADODB.Command
    Dim objParm1 As New ADODB.Parameter
    Dim objRs As New ADODB.Recordset
    Dim ServerName As String, DatabaseName As String


   ServerName = "YourServerName"
   DatabaseName = "YourDatabaseName"

   ' Specify the OLE DB provider.
   cn.Provider = "sqloledb"

   ' Set SQLOLEDB connection properties.
   cn.Properties("Data Source").Value = ServerName
   cn.Properties("Initial Catalog").Value = DatabaseName
   cn.CursorLocation = adUseClient ' <---#####ADD THIS

   ' Windows authentication.
   cn.Properties("Integrated Security").Value = "SSPI"


  ' Set CommandText equal to the stored procedure name.
   objCmd.CommandText = procName 
   objCmd.CommandType = adCmdStoredProc

  ' Open the database.
  cn.Open

  objCmd.ActiveConnection = cn

  ' Automatically fill in parameter info from stored procedure.
  objCmd.Parameters.Refresh



  ' Set the param value.
   objCmd(1) = procVal


  Set call_proc = objCmd.Execute
End Function