在Excel消息框中显示来自SQL Server过程调用的结果

我在Excel中有一个VBA子。 它需要调用SQL Server过程,并在消息框中显示调用的结果。 (主要是因为我维护别人的代码 – 否则,我不会使用Excel。)

我创build我的SQL语句来调用过程。 我有subs打开连接。 但是在显示那个过程调用的结果的过程中我仍然错过了一些东西。

以下是我到目前为止:

Dim Today As Date Dim result As Date Dim sSQLStatement As String Dim strDate As String Dim Recordset As ADODB.Recordset Today = DateTime.Now() result = DateSerial(Year(Today), Month(Today) - 1, 1) strDate = Year(result) & "-" & Format(Month(result), "00") & "-" & Format(Day(result), "00") DBOpen sSQLStatement = "set nocount on; EXEC [MySchema].[dbo].[MyProcedure] @END_DATE = N'" & strDate & "'" MsgBox sSQLStatement Dim i As Long Dim Ary Dim strMsg As String Set Recordset = New ADODB.Recordset With Recordset .ActiveConnection = cnPubs 'this is defined elsewhere, used in the DBOpen call, and works 'I can call the execute and it works, but it fails here when I try to assign the results to the recordset Recordset = cnPubs.Execute(sSQLStatement) 'I found this online and don't know yet if it works. I have to get past the statement above first. If Not Recordset.EOF Then Ary = Recordset.GetRows For i = 0 To UBound(Ary, 2) If i = 0 Then strMsg = Ary(0, i) Else strMsg = strMsg & ", " & Ary(0, i) End If Next i MsgBox strMsg, , UBound(Ary, 2) + 1 & " records" End If .Close End With DBClose 

所以,如果我自己调用cnPubs.Execute(sStateStatement),我可以告诉它正在运行。 我打开并closures连接就好了。 但它应该返回一组几行,我需要显示。 我不想把它们写到电子表格的任何地方 – 它们应该只显示在一个消息框中。

更改

 Recordset = cnPubs.Execute(sSQLStatement) 

 recordset.open sSQLStatement, cnPubs