ADO Recordset Not Staying Open in VBA - “Operation is not allowed when the object is closed”

后端 未结 3 908
我在风中等你
我在风中等你 2021-01-21 07:41

I don\'t really understand what has happened here. I\'m using Excel VBA to connect to a SQL Server Express database and return an ADO Recordset. I had it working initially, but

3条回答
  •  無奈伤痛
    2021-01-21 08:22

    Please try the following code:

    Public Sub AdoTestConnection()
    Dim conServer As ADODB.Connection
    Dim rstResult As ADODB.Recordset
    Dim strDatabase As String
    Dim strServer As String
    Dim strSQL As String
    
    strServer = "YourServerName"
    strDatabase = "YourDatabaseName"
    
    Set conServer = New ADODB.Connection
    conServer.ConnectionString = "PROVIDER=SQLOLEDB; " _
        & "DATA SOURCE=" & strServer & "; " _
        & "INITIAL CATALOG=" & strDatabase & "; " _
        & "User ID=" & strLogin & ";" _
        & "Password=" & strPassword
    On Error GoTo SQL_ConnectionError
    conServer.Open
    On Error GoTo 0
    
    Set rstResult = New ADODB.Recordset
    strSQL = "set nocount on; "
    strSQL = strSQL & "select  1 "
    rstResult.ActiveConnection = conServer
    On Error GoTo SQL_StatementError
    rstResult.Open strSQL
    On Error GoTo 0
    
    If Not rstResult.EOF And Not rstResult.BOF Then
        MsgBox "Connection worked. Server returned " & rstResult.Fields(0).Value
    Else
        MsgBox "Connection worked. The server did not return any value."
    End If
    
    Exit Sub
    
    SQL_ConnectionError:
    MsgBox "Problems connecting to the server." & Chr(10) & "Aborting..."
    Exit Sub
    
    SQL_StatementError:
    MsgBox "Connection established. Yet, there is a problem with the SQL syntax." & Chr(10) & "Aborting..."
    Exit Sub
    
    End Sub
    

    If the above code works then you can change the SQL command with your procedure like so:

    strSQL = "set nocount on; "
    strSQL = strSQL & "exec StoredProcedureName @Parm1 = " & intValue1 & ", "
    strSQL = strSQL & "                         @Parm2 = " & intValue2 & ", "
    strSQL = strSQL & "                         @Parm3 = " & intValue3 & ", "
    strSQL = strSQL & "                         @Parm4 = N'" & strValue1 & "', "
    strSQL = strSQL & "                         @Parm5 = N'" & strValue2 & "', "
    strSQL = strSQL & "                         @Parm6 = N'" & strValue3 & "', "
    strSQL = strSQL & "                         @Parm7 = N'" & strValue4 & "' "
    

    I strongly favor this approach over your current because it is much easier to debug. If you ever run into a problem with your SQL syntax you can simply request the content of strSQL like so:

    Debug.Print strSQL
    

    Then you can copy the result of that into SQL Server Management Studio (SSMS) and verify the result there. You may even come to the conclusion that you do not want to use a stored procedure and copy the entire content of the SP into your VBA code.

提交回复
热议问题