【问题标题】:run-time error '3704' operation is not allowed when the object is closed关闭对象时不允许运行时错误“3704”操作
【发布时间】:2016-02-29 09:23:19
【问题描述】:

这里是菜鸟。 excel中的这个vba代码应该使用ADO连接到sql 2008,运行查询并在excel中填充sheet1。现在,标题错误不断弹出在这一行 " Sheet1.Range("A1").CopyFromRecordset rst".

Sub Code1()

Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim SqlQuery As String

Application.ScreenUpdating = False

Const stADO As String = "Provider=SQLOLEDB.1;Password=NOPWDHERE;Persist Security Info=True;User ID=sa;Initial Catalog=StockControl;Data Source= PCSMIS01"

Set wbBook = ActiveWorkbook
Set WsSheet = wbBook.Worksheets(1)


SqlQuery = " SELECT * FROm dbo.Site "

Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset

With cnt
        .CursorLocation = adUseClient
        .Open stADO
        .CommandTimeout = 0
        Set rst = .Execute(SqlQuery)
End With

Sheet1.Range("A1").CopyFromRecordset rst

'With rst
'        .ActiveConnection = cnt
'        .Open SqlQuery
'        Sheet1.Range("A1").CopyFromRecordset rst
'        .Close
'End With

rst.Close
cnt.Close

Set rst = Nothing
Set cnt = Nothing

End Sub

我也尝试过使用注释代码将数据复制到工作表中的替代方法。我已经尽我所能在互联网上研究了类似的主题,但我现在更加困惑。请帮忙。

【问题讨论】:

  • Sheet1 替换为WsSheet 应该可以! ;)
  • 一般情况下:不要使用 sa 帐户进行此类查询。不要将您的 sa 帐户的密码粘贴到公共论坛中;)
  • 您好,感谢您的回复。我尝试过使用 wsSheet 并且在同一个地方弹出相同的错误。密码仅用于说明目的。希望 sn-p 尽可能接近代码。

标签: vba sql-server-2008 excel


【解决方案1】:

Sheet1(未引用)替换为WsSheet

Sub Code1()

Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim SqlQuery As String

Application.ScreenUpdating = False

Const stADO As String = "Provider=SQLOLEDB.1;Password=NOPWDHERE;Persist Security Info=True;User ID=sa;Initial Catalog=StockControl;Data Source= PCSMIS01"

Set wbBook = ActiveWorkbook
Set WsSheet = wbBook.Worksheets(1)


SqlQuery = " SELECT * FROm dbo.Site "

Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset

With cnt
        .CursorLocation = adUseClient
        .Open stADO
        .CommandTimeout = 0
        Set rst = .Execute(SqlQuery)
End With

WsSheet.Range("A1").CopyFromRecordset rst

'With rst
'        .ActiveConnection = cnt
'        .Open SqlQuery
'        Sheet1.Range("A1").CopyFromRecordset rst
'        .Close
'End With

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-24
    • 2019-02-18
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多