我尝试通过VBA从excel 2007调用存储过程。我想从存储过程返回到excel表。但是我在Worksheets(“Sheet1”)上得到“关闭对象时不允许运行时3074操作”。范围(“A1”)。CopyFromRecordset objMyRecordset。
我做了很多没有结论的搜索。我只是想知道是否需要先在MSSQL存储过程中定义一个表变量,然后插入它。
下面是我写的代码:** * *** 存储过程sp_weekly * ***
select [field1], [field2] into mytable_2 from mytable_1
select a.*, b.field4 from mytable_2 a
inner mytable_3 b on join a.field1 = b.field3
** * ** * *
Option Explicit
Sub OpenConnection()
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyRecordset As ADODB.Recordset
Dim ConnectionString As String
Dim CommandText As String
Set objMyConn = CreateObject("ADODB.Connection")
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
ConnectionString = "Provider=sqloledb;Data Source=abcsql,1433;Initial Catalog=admin;User Id=sa;Password=1234abcd;"
objMyConn.Open ConnectionString
Set objMyCmd.ActiveConnection = objMyConn
CommandText = "exec [admin].[dbo].[sp_weekly]"
objMyCmd.CommandType = adCmdText
Set objMyRecordset.Source = objMyCmd
objMyRecordset.Open
Worksheets("Sheet1").Range("A1").CopyFromRecordset objMyRecordset
end
答案 0 :(得分:0)
您收到错误,因为查询没有返回任何结果。要执行存储过程,您需要执行以下操作:
Sub PullFromStoredProc()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Set cn = New ADODB.Connection
cn.Open _
"Provider=sqloledb;" & _
"Data Source=abcsql,1433;" & _
"Initial Catalog=admin;" & _
"User Id=sa;" & _
"Password=1234abcd;"
Set cmd = New ADODB.Command
With cmd
.CommandType = adCmdStoredProc
.CommandText = "[admin].[dbo].[sp_weekly]"
.ActiveConnection = cn
Set rs = .Execute
End With
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
cn.Close
End Sub