【发布时间】: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