【问题标题】:Getting Object Variable, Block Variable not set error trying to use VBA to pull SQL Server stored procedure获取对象变量,块变量未设置错误尝试使用 VBA 提取 SQL Server 存储过程
【发布时间】:2019-06-30 19:53:16
【问题描述】:

我正在尝试使用 VBA 从 SQL Server 中提取存储过程。我能够从服务器中提取基本 SQL 代码,但是当尝试将复杂代码与存储过程一起使用时,我收到错误 91:对象变量或未设置块变量。无法确定我需要设置什么才能使其正确运行。

done 不带参数的存储过程,并且没有列出参数的代码。我尝试了本论坛其他主题的一些参数代码,但没有任何变化

删除 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

【问题讨论】:

  • 哪行代码触发了错误?
  • 你没有 Set cmd 对象 - 你需要这样做。
  • @CindyMeister 说“你没有设置 cmd 对象”评论将是一个很好的值得投票的答案 btw ;-)
  • @MathieuGuindon 如果我知道设置它的正确语法 to 我会回答 :-) 因为当时我在移动设备上,所以我不能'不研究它,但认为 OP 或其他人可以,一旦清楚为什么会发生错误。对我来说,这样的事情是接近“不可复制”的关闭......

标签: vba stored-procedures adodb


【解决方案1】:

"Object [or With block] variable not set" 是 VBA 等价于其他语言的“空引用异常”,当您尝试访问对象的成员时,当该对象的引用为 null 时会发生错误,或者在VBA 术语,Nothing

这正是这里发生的事情:

cmd.ActiveConnection = conn

cmd 对象已声明,但从未初始化。 Set 将其添加到 New 类的 New 实例以解决问题:

Set cmd = New ADODB.Command
cmd.ActiveConnection = conn

错误信息的“With block”部分指的是With块语法:

Dim cmd As ADODB.Command
With cmd ''<< error 91 here
    '...
End With

您可以使用With NewWith 块持有对象引用,而无需声明局部变量:

With New ADODB.Command
    '...
End With

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多