2017-07-19 75 views
0

我在Excel工作簿下面的代碼,我從this page.複製Excel的VBA - 運行SQL存儲過程中的錯誤

代碼:

Sub Button1_Click() 

Dim con As ADODB.Connection 
Dim cmd As ADODB.Command 
Dim rs As ADODB.Recordset 
Dim WSP1 As Worksheet 

Set con = New ADODB.Connection 
Set cmd = New ADODB.Command 
Set rs = New ADODB.Recordset 

'''Clear extract area''' 
Worksheets("Extract").UsedRange.Delete 

'''Log into SQL Server''' 
con.Open "Provider = SQLOLEDB;" & _ 
     "Data Source = MySource;" & _ 
     "Initial Catalog = MyDB;" & _ 
     "User ID = MyID;" & _ 
     "Password = MyPassword;" 
cmd.ActiveConnection = con 

'''Set up parameters for stored procedure''' 
cmd.Parameters.Append cmd.CreateParameter("startDate", adDate, adParamInput, , Range("C2")) 
cmd.Parameters.Append cmd.CreateParameter("endDate", adDate, adParamInput, , Range("C3")) 

cmd.CommandText = "DB.StoredProc" 
Set rs = cmd.Execute(, , adCmdStoredProc) 

Set WSP1 = Worksheets("Extract") 
WSP1.Activate 
If rs.EOF = False Then WSP1.Cells(1, 1).CopyFromRecordset rs 

rs.Close 
Set rs = Nothing 
Set cmd = Nothing 

con.Close 
Set con = Nothing 

End Sub 

我上線「如果RS以下錯誤消息.EOF = False Then'

「當對象關閉時不允許操作。」

這是我第一次使用這些功能。我做錯了什麼?

另外,我是否正確設置了多個參數?

---快速編輯--- 不知道是否值得一提的是,我將日期格式設置爲yyyy-mm-dd,因爲它在SQL服務器中。

回答

0
cmd.CommandText = "DB.StoredProc" 

應該是您的存儲過程的實際名稱 - 除非您實際上已將其命名爲StoredProc?

+0

我將名稱更改爲「DB.StoredProc」以發佈問題。這是我係統上的真實姓名。 – Jamsandwich

+0

對不起,剛剛發現它 昏暗的rs作爲ADODB.Recordset 應該是 昏暗的rs作爲新的ADODB.Recordset –

+0

沒問題。我按照你的說法改變了它,但沒有運氣。 – Jamsandwich

0

這裏有兩個選項供您考慮。

Option Explicit 

Sub RunSProc() 

'USE [Northwind] 
'GO 
'DECLARE @return_value int 
'EXEC @return_value = [dbo].[TestNewProc] 
'  @ShipCountry = NULL 
'SELECT 'Return Value' = @return_value 
'GO 

Dim con As Connection 
Dim rst As Recordset 
Dim strConn As String 

Set con = New Connection 
strConn = "Provider=SQLOLEDB;" 
strConn = strConn & "Data Source=YOUR_SERVER_NAME;" 
strConn = strConn & "Initial Catalog=YOUR_DB_NAME;" 
strConn = strConn & "Integrated Security=SSPI;" 

con.Open strConn 

'Put a country name in Cell E1 
Set rst = con.Execute("Exec dbo.TestNewProc '" & ActiveSheet.Range("E1").Text & "'") 

'The total count of records is returned to Cell A5 
ActiveSheet.Range("A5").CopyFromRecordset rst 

rst.Close 
con.Close 

End Sub 


Sub TryThis() 

'USE [Northwind] 
'GO 
'DECLARE @return_value int 
'EXEC @return_value = [dbo].[Ten Most Expensive Products] 
'SELECT 'Return Value' = @return_value 
'GO 

Dim con As Connection 
Dim rst As Recordset 

Set con = New Connection 
con.Open "Provider=SQLOLEDB;Data Source=YOUR_SERVER_NAME;Initial Catalog=YOUR_DB_NAME;Integrated Security=SSPI;" 

Set rst = con.Execute("Exec dbo.[Ten Most Expensive Products]") 
'Results of SProc are returned to Cell A1 
ActiveSheet.Range("A1").CopyFromRecordset rst 

rst.Close 
con.Close 
End Sub 
1

我解決了這個問題,在我的存儲過程中添加了SET NOCOUNT ON

我最初並不確定自己是否有權進行此項更改。但我有一個新問題。如果我只使用單個參數,但在使用多個參數時不起作用,它將起作用。

我將關閉此主題,進行一些研究並可能會開啓一個新主題。

感謝您的幫助。