2016-02-28 92 views
1

我已經使用MS Access 2010中的VBA創建了一個函數來執行SQL Server存儲過程並在ADODB.Recordset對象中返回值。但是,我無法使用從ADODB連接返回的記錄集來設置MS Access窗體的RecordSource或Recordset。從ADODB.recordset設置表單的VBA記錄集時出錯

下面就是你會發現代碼摘錄:call_proc的

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

函數頭:

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

如果我遍歷了objRS,做一個Debug.Print我能看到所有記錄。所以我知道數據在那裏。只是不知道如何解決將數據綁定到表單的錯誤。 的代碼下面返回錯誤的行:

Set Forms("form1").Recordset = objRs 

enter image description here

任何暗示欣然接受。 預先感謝您。

+0

嗨@hansUp,則返回 「無」 – codeBarer

+0

只是一個供參考,Debug.Print類型名(objRS)不return Recordset – codeBarer

+0

有關將表單綁定到ADO記錄集的信息,請參見此[資源](https://support.microsoft.com/zh-cn/kb/281998)。它可能涉及連接OLEDB/ODBC驅動程序和記錄集類型(即,adLockOptimistic,adOpenDynamic)。請顯示您的完整連接代碼。 – Parfait

回答

1

修正了它。問題出在我的call_proc函數中。當我打開ADODB.Recordset時,我沒有設置光標位置。見下面,我添加代碼 「」 < --- #####添加此」

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 
相關問題