我正在尝试使用VBA从SQL Server中提取存储过程。我能够从服务器中提取基本的SQL代码,但是当尝试在存储过程中使用复杂的代码时,出现错误91:对象变量或未设置块变量。无法确定我需要设置什么才能使其正常运行。
已完成的存储过程没有参数,并且没有列出参数的代码。我在这个论坛上尝试了其他主题的一些参数代码,但是没有变化
删除cmd行并仅针对SQL代码(SELECT * FROM Table)运行它就可以了
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
答案 0 :(得分:1)
“未设置对象[或带块]变量”是VBA等效于其他语言的“空引用异常”,当该对象的引用为$ ./bin/strarr
please enter ONLY capital letters, (TYPE 'done' to exit)
DOLPHINS
SAINTS
STEELeRS
error: letter must be capital
STEELERS
VIKINGS
done
this is the result you entered
DOLPHINS
SAINTS
STEELERS
VIKINGS
时尝试访问对象的成员时会发生此错误,或使用VBA术语null
。
这正是这里发生的事情:
Nothing
cmd.ActiveConnection = conn
对象已声明,但从未初始化。 cmd
将其Set
类的New
实例中解决该问题:
ADODB.Command
错误消息的“带有块”部分是指Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
块语法:
With
您可以使用Dim cmd As ADODB.Command
With cmd ''<< error 91 here
'...
End With
将对象引用保存在With New
块中,而无需声明局部变量:
With