我在MS Access 2010中使用VBA创建了一个函数来执行SQL Server存储过程并在ADODB.Recordset Object中返回值。但是,我无法使用从ADODB连接返回的记录集设置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,我可以看到所有记录。所以我知道数据存在。只是不知道如何解决将数据绑定到表单的错误。 下面的代码行返回错误:
Set Forms("form1").Recordset = objRs
任何暗示接受的建议。 先感谢您。
答案 0 :(得分:1)
修正了它。问题出在我的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