【问题标题】:Object variable or With block variable not set.未设置对象变量或 With 块变量。
【发布时间】:2018-12-11 16:09:45
【问题描述】:

我正在尝试将 SQL Server 连接到 Access。我在一个模块中有连接功能。我在另一个模块中调用了这个函数。

这是我模块中的代码:

'Variabel voor SQL Server Connectie
Public SQLConnectie As ADODB.Connection

'Connecten met SQL Server
Public Function DBConn() As ADODB.Connection
If Not (SQLConnectie Is Nothing) Then
    Set SQLConnectie = New ADODB.Connection
    With SQLConnectie
        .CommandTimeout = 15
        .Mode = adModeReadWrite
        .ConnectionString = "Provider=SQLNCLI11;Server=dafehvmvdsql3;Database=PROVOMotorenfabriek;Integrated Security=SSPI; Persist Security Info=False"
        .Open
    End With
End If

Set DBConn = SQLConnectie
Set SQLConnectie = Nothing
End Function

在SQL Server中执行存储过程的模块中的代码如下:

Call DBConn.Execute("EXEC spStoringToevoegen " & productielijnMW & ", " & Forms(Formnaam)!cbLijngedeelte & ".............etc

我收到错误:对象变量或未设置块变量。我找到的每个答案都说我需要将 set 放在一些变量的前面,但我找不到应该是哪个。

提前致谢,

【问题讨论】:

  • 我的 VBA 相当生锈,但在这段代码中你说的是如果不是(SQLConnectie 是一个 NULL 值),不是吗?由于它最初是一个 NULL 值,因此它始终是一个 NULL 值,它也会将 SQLConnectie 设置为 NULL。此外,很高兴这段代码不起作用并阻止您使用这样的 SQL 命令。您应该使用参数(检查 SQL 注入攻击)。
  • Cetin 可能是对的。这段代码还包含两个主要的设计缺陷: 1. 一个连接可能是无效的,但仍然不是什么都不是。例如,封闭的连接不是什么都不是。您不应该持久存储连接,如果这样做,您应该添加更多检查。 2. 你的代码对 SQL 注入很开放。即使所有用户都受信任,这仍然可能导致意外错误。
  • @CetinBasoz 你是这个意思吗? .Parameters.Append .CreateParameter("Productielijn", adTinyInt, adParamInput, , productielijnMW)
  • 你们能给我一些关于如何更好地实现这一点的提示吗?我是连接到 SQL Server 的初学者
  • 只需废弃If 条件,不要将SQLConnectie 声明为第一个问题的全局变量。对于第二个问题,使用parameters(这意味着创建一个ADODB.Command 对象,而不仅仅是调用.Execute,底部是关于ADODB)。

标签: sql-server ms-access stored-procedures vba


【解决方案1】:

将此添加到示例参数中。

正如我所说,我的 VBA 非常生疏(而且我发现 VBA 使用起来特别奇怪的语言,添加 Access 对我来说听起来很痛苦)。如果您使用其他一些后端(以及语言)会容易得多。无论如何,这是一个带有 VBA (Excel) 参数的示例:

Sub Macro1()
   Dim oRecordset1 As ADODB.Recordset
   Dim oConnection As ADODB.Connection
   Dim oCommand As ADODB.Command
   Dim oParameter1 As ADODB.Parameter
   Dim oParameter2 As ADODB.Parameter


  Set oConnection = New ADODB.Connection
  Set oCommand = New ADODB.Command

  oConnection.ConnectionString = "Provider=SQLNCLI11.0;Data Source=.\SQLExpress;Trusted_connection=Yes"

  oConnection.Open
  oCommand.ActiveConnection = oConnection
  oCommand.CommandType = 4
  oCommand.CommandText = "Northwind.dbo.[CustomersSelectLike]"

  Set oParameter1 = oCommand.CreateParameter("@country", 130, 1, -1) ' adWChar
  oCommand.Parameters.Append oParameter1
  oCommand.Parameters("@country").Value = "USA"

  Set oParameter2 = oCommand.CreateParameter("@customer", 130, 1, -1)
  oCommand.Parameters.Append oParameter2
  oCommand.Parameters("@customer").Value = "%"

  Set oRecordset = oCommand.Execute()
  Sheet1.Range("A1").CopyFromRecordset (oRecordset)
End Sub

【讨论】:

    猜你喜欢
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多