尝试多次在excel(vba宏)中运行SP

时间:2015-07-20 15:29:23

标签: excel vba excel-vba stored-procedures

我正在尝试在excel宏(按钮)中的函数内运行SP:

Sub Button13_Click()
    Call exec_sp_GetLoan_CFM_Info_by_customerID("B3", 2, 1)
    Call exec_sp_GetLoan_CFM_Info_by_customerID("B24", 3, 1)
    Call exec_sp_GetLoan_CFM_Info_by_customerID("B45", 4, 1)
    Call exec_sp_GetLoan_CFM_Info_by_customerID("B66", 5, 1)
    Call exec_sp_GetLoan_CFM_Info_by_customerID("B86", 6, 1)
End Sub

SP每次都返回一行,我试图用每个结果集写一行。发生的事情是,我在电子表格中获得了一行,例如,如上所示,我只会从B3获得第2行结果集为custID。如果我注释掉第一行,我只会得到第3行,包含来自B24的custID的结果,依此类推。我永远不会超过1行,我不明白为什么(我对vb和excel宏完全陌生)。谁能解释一下发生了什么?即使我没有清除任何行,也会发生这种情况......谢谢!

更新:如果我为每个'呼叫'设置了单独的按钮。功能,运行良好...

Function exec_sp_GetLoan_CFM_Info_by_customerID(custIDcell As String, stRow As Integer, stCol As Integer)
 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

 Application.DisplayStatusBar = True
 Application.StatusBar = "Contacting SQL Server..."

' Log in
 con.Open "Provider=SQLOLEDB;Data Source=xxxx;Initial Catalog=xxxx ID=xxxx;Password=xxxx;"
 cmd.ActiveConnection = con

 ' Set up the parameter for the Stored Procedure
 cmd.Parameters.Append cmd.CreateParameter("custID", adVarChar, adParamInput, 8, Range(custIDcell).Text)

 Application.StatusBar = "Running stored procedure..."
 cmd.CommandText = "sp_GetLoan_CFM_Info_by_customerID"
 Set rs = cmd.Execute(, , adCmdStoredProc)

 Set WSP1 = ActiveWorkbook.Worksheets("CIFInfo")
 WSP1.Activate

 'clear row
 WSP1.Rows(stRow).Clear

 If rs.EOF = False Then WSP1.Cells(stRow, stCol).CopyFromRecordset rs

 'cmd.Parameters("custID").Value = Range("B24").Text

 'cleanup
 rs.Close
 Set rs = Nothing
 Set cmd = Nothing

 con.Close
 Set con = Nothing

 Application.StatusBar = "Data successfully updated."

End Function

1 个答案:

答案 0 :(得分:0)

初学者(Excel)错误...在第一次使用SP调用该函数后,活动工作表将从输入更改为另一个,因此后续调用使用空输入参数完成! 从帖子中看出来并不明显..抱歉!!