从excel 2007 VBA打开mssql存储过程并获取数据到excel

时间:2012-02-27 21:42:15

标签: excel-vba excel-2007 vba excel

我尝试通过VBA从excel 2007调用存储过程。我想从存储过程返回到excel表。但我得到了 在运行工具栏(“Sheet1”)上关闭对象时'运行时3074不允许操作。范围(“A1”)。CopyFromRecordset objMyRecordset

下面是我写的代码:

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

1 个答案:

答案 0 :(得分:1)

您需要指定您正在调用过程,如下所示:

...

Set objMyCmd.ActiveConnection = objMyConn
CommandText = "sp_weekly"
objMyCmd.CommandType = adCmdStoredProc

...