I'm attempting to pull a stored procedure from SQL Server using VBA. I'm able to pull basic SQL Code from the server, but when trying to use a complex code with a stored procedure, I'm getting a Error 91: Object Variable or With block variable not set. Haven't been able to determine what I need to set to make this run correctly.
The stored procedure with done without parameters, and do not have code for parameters listed. I've tried some parameter code from other topics in this forum, but no change
Removing the cmd lines and running it just for a SQL Code (SELECT * FROM Table) did work
Sub ConnectSQL()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Dim sConnString As String
'Create Connection String
sConnString = "Provider=SQLOLEDB;Data Source=ServerName;" & _
"Initial Catalog=DatabaseName;" & _
"User ID=ID;" & _
"Password=Password;" & _
"Integrated Security=SSPI;"
'Create Connection and Recordset Objects
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
'Open Connection and Execute
conn.Open sConnString
cmd.ActiveConnection = conn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "Paint558Ranking"
Set rs = cmd.Execute
'Check If Data
If Not rs.EOF Then
'Transfer Result
Sheets("Sheet1").Range("A1").CopyFromRecordset rs
'Close record
rs.Close
Else
MsgBox "Error: No Records Returned.", vbCritical
End If
'Clean Up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
Setthecmdobject - you need to do that.