【问题标题】:"Object Required" error“需要对象”错误
【发布时间】:2016-01-30 04:13:31
【问题描述】:

我有一个 SQL 查询用完了 Excel。目标是运行查询并将数据粘贴到指定位置:

    Public Function Pull_SQL_Data()

        ''''On Error GoTo Err:

Worksheets("Data").Select
Range("B7").Select
Do Until ActiveCell = ""
ActiveCell.Offset(1).Select
Loop
Range("B:S", ActiveCell.Offset(-1, 3)).ClearContents

Worksheets("Data").Select
Range("B7").Select

Dim cnPubs As New ADODB.Connection
Dim strConn As String
Dim rstRecordsets As New ADODB.Recordset
Dim intColIndex As Integer
Dim strSQL As Variant

Application.ScreenUpdating = False
Application.Cursor = xlWait

Set cnPubs = New ADODB.Connection
Set rsPubs = New ADODB.Recordset

Set outCell = Sheets("Data").Range("B7")

strSQL = Sheets("SQL").Range("G1")

strConn = "PROVIDER=SQLOLEDB;"
cnPubs.CommandTimeout = 240
strConn = strConn & "DATA SOURCE=CFS-Serversql;INITIAL CATALOG=UserAnalysis;"
strConn = strConn & "INTEGRATED SECURITY=sspi;"

cnPubs.Open strConn
With rsPubs
     .ActiveConnection = cnPubs
     .Open strSQL, cnPubs, adOpenStatic, adLockReadOnly, adCmdText


Sheets("Data").Range("B7:S500").ClearContents
Sheets("Data").Range("B4").CopyFromRecordset rsPubs


End With

rsPubs.Close
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing

Application.Cursor = xlDefault

Exit Function

Err:
    MsgBox "The following error has occured-" & vbCrLf & vbCrLf & VBA.Error, vbCritical, "SQL Connection"
    MsgBox VBA.Err

    Application.Cursor = xlDefault
    Worksheets("DWH").Select
    Range("A1").Select

End Function

运行时我得到:

发生以下错误 - 需要对象”错误代码 424。

为什么我会遇到这个问题?

【问题讨论】:

  • Set .ActiveConnection = cnPubs
  • 我在哪里插入那行@TimWilliams?
  • 注释掉On Error GoTo Err: - 哪一行有问题?
  • 你没有向DBO声明或分配任何东西
  • CopyFromRecordset 需要一个记录集作为参数

标签: sql vba sql-server-2008 excel


【解决方案1】:

这行得通吗?

Public Function Pull_SQL_Data()

    Dim ws As Worksheet
    Dim cnPubs As ADODB.Connection
    Dim rsPubs As ADODB.Recordset
    Dim strConn As String
    Dim strSQL As Variant

    Set ws = Worksheets("Data")

    Set cnPubs = New ADODB.Connection
    Set rsPubs = New ADODB.Recordset

    strSQL = Sheets("SQL").Range("G1").Value

    strConn = "PROVIDER=SQLOLEDB;DATA SOURCE=CFS-Serversql;" & _
              "INITIAL CATALOG=UserAnalysis;INTEGRATED SECURITY=sspi;"

    cnPubs.Open strConn

    rsPubs.Open strSQL, cnPubs, adOpenStatic, adLockReadOnly, adCmdText

    ws.Range("B7:S500").ClearContents

    If Not rsPubs.EOF Then
        ws.Range("B4").CopyFromRecordset rsPubs
    Else
        MsgBox "No records were returned!"
    End If

    rsPubs.Close
    cnPubs.Close

End Function

【讨论】:

  • 我收到错误关闭对象时不允许操作。运行时错误“3704”在线“如果不是 rsPubs.EOF Then”我感谢您的洞察力
  • Rspubs 应该在那个时候打开 - 你使用的是我发布的确切代码吗?
  • 是的,确切的代码与引用有关吗? @蒂姆·威廉姆斯
  • 如果您没有设置正确的引用,那么您将收到有关“用户定义类型”的编译时错误。我从未见过Open 调用无法打开记录集而不会引发错误。
  • 查询是否有问题?但是查询在 SQL 中运行良好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多