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

时间:2017-06-13 18:18:08

标签: sql-server excel vba excel-vba stored-procedures

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

我创建了我的SQL语句来调用该过程。我有打开连接的潜艇。但是,在显示该程序调用的结果的过程中,我仍然遗漏了一些东西。

这是我到目前为止所拥有的:

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(sSQLStatement),我可以告诉它正在运行。我打开并关闭连接就好了。但它应该返回一组几行,我需要显示它。我不想在任何地方将这些内容写入电子表格 - 它们应该只显示在消息框中。

1 个答案:

答案 0 :(得分:3)

更改

Recordset = cnPubs.Execute(sSQLStatement)

recordset.open sSQLStatement, cnPubs