在VBA中使用记录集时如何解决错误7965?

时间:2019-07-19 21:51:57

标签: sql-server ms-access-2013

我正在使用VBA中的子表单(ms access 2013)。我正在尝试使用从存储过程(SQL-Server v17.9.1)返回的数据加载2个文本框,当我在Management Studio中运行proc时,我得到3行返回,只有2列员工的姓名缩写和总数他们的客户。

当我尝试将表单的记录集(Set Me.Recordset = rst)设置为查询返回的记录集时,出现以下错误:

  

“错误7965:您输入的对象不是有效的Recordset属性。”

这是一个现有的访问数据库(2013),我公司希望保留访问表单作为前端,但将所有数据和操作都指向SQL-Server(V17.9.1)数据库。

Private Sub Form_Load()
    Dim strError As String
    Dim cnn As ADODB.Connection
    Dim cmd As ADODB.Command
    Dim rs As ADODB.Recordset

    On Error GoTo Err_Handler

    Set cnn = New ADODB.Connection
    cnn.Open gconConnectOLEDB
    Set cmd = New ADODB.Command
    cmd.CommandType = adCmdStoredProc
    cmd.CommandText = "spGetInitialsAndCounts"
    cmd.ActiveConnection = cnn

    Set rs = New ADODB.Recordset
    Set rs = cmd.Execute

    Set Me.Recordset = rs  '<---- This is where the error is occurring
    Me.Rep.ControlSource = "Rep"
    Me.CountOfRep.ControlSource = "CountOfActiveClients"

Exit_Handler:
    On Error Resume Next

    If LenB(strError) Then
        MsgBox strError, vbCritical, Me.Name & ".Form_Load"
    End If

    If Not(rs Is Nothing) Then
        rs.Close
        Set rs = Nothing
    End If

    If Not(cnn Is Nothing) Then
       If Not(cnn.State = adStateClosed) Then cnn.Close
      Set cnn = Nothing
    End If

    Exit Sub
Err_Handler:
   strError = "Error " & Err.Number & ": " & Err.Description
   Resume Exit_Handler
End Sub

最令人沮丧的是,其他形式使用了类似的代码,并且文本框正确填充。

感谢您提供的任何帮助和见解。

2 个答案:

答案 0 :(得分:2)

经过大量研究,最终需要将ADODB Recordset的“ CursorLocation”属性设置为adUseClient。可以将“ CursorLocation”属性设置为“ adUseServer”或“ adUseClient”。就我而言,我根本没有为它指定任何值,它默认为adUseServer。 我的更正代码的片段如下:

Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset

Set cnn = New ADODB.Connection
cnn.Open gconConnectOLEDB

With rs
  Set .ActiveConnection = cnn
      .Source = "EXEC spSQLServerProc "
      .LockType = adLockOptimistic
      .CursorType = adOpenKeyset
      **.CursorLocation = adUseClient**
      .Open
End With
Set Me.Recordset = rs

答案 1 :(得分:0)

Microsoft允许binding forms to ado recordset 因此,我怀疑您的记录集未返回任何内容。 要检查此内容,请使用此代码

 if rs.EOF then
    debug.print "empty recordset"
 else 
   Set Me.Recordset = rs  '<---- This is where the error is occurring
 end if 

因此,如果您得到空记录,请尝试找出为什么存储过程返回3行而adodb什么也不返回。 第一个检查将是gconConnectOLEDB是有效的连接字符串吗?