0

我正在尝试将带有存储过程的 SQLServer 数据库中的数据直接提取到 Excel 电子表格中。我正在尝试制作一个仪表板,允许用户选择他们想要查看的特定月份并提取该月的数据。提取数据后,仪表板将自动计算用户将看到哪些图表等。不过,这是我第一次从 ADODB 连接中提取数据,但在尝试实际提取数据时遇到了问题。我在尝试从记录集中复制的行上收到错误“'GO' 附近的语法不正确”。任何帮助将不胜感激。

编辑:这是新代码。我现在收到运行时错误 3704:对象关闭时无法执行此操作。当我尝试从记录集中复制时,它仍然会发生。

Sub btnPullData_Click()
Dim objConn As New ADODB.Connection
Dim objRecordset As ADODB.Recordset
Dim rngTableCell As Range
Dim drpPicker As DropDown
Dim strDropVal As String
Dim objCommand As New ADODB.Command


Set rngTableCell = Range("celFirstInTable")
rngTableCell.ListObject.DataBodyRange.Rows.Delete

Set drpPicker = ThisWorkbook.Sheets("Dashboard").DropDowns("dropFis_Month")
strDropVal = Format(drpPicker.List(drpPicker.ListIndex), "mmm-yy")

objConn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=KPITRACKER;Data Source=JEFFSQL"

With objCommand
    .CommandType = adCmdStoredProc
    .CommandText = "DynamicPhonesSP"
    .Parameters.Append .CreateParameter("@TimeSum", advarWChar, , 1, "m")
    .Parameters.Append .CreateParameter("@TimeSum1", advarWChar, , 1, "d")
    .Parameters.Append .CreateParameter("@TimeParam", advarWChar, , 20, strDropVal)
    .Parameters.Append .CreateParameter("@RptLevel", adInteger, , , 1)
    .ActiveConnection = objConn
    Set objRecordset = .Execute
End With

ThisWorkbook.Sheets("Data").Range("B6").CopyFromRecordset objRecordset

objRecordset.Close
Set objRecordset = Nothing
objConn.Close
Set objConn = Nothing

End Sub
4

1 回答 1

1

您可以更直接地调用存储过程:(可能是一些语法问题)

Sub btnPullData_Click()
    Dim lCon as New ADODB.Connection
    Dim lCommand as New ADODB.Command
    Dim lRecordset as ADODB.Recordset
    Dim lR As Range
    Dim lMonth as Variant

    Set lR = Range("celFirstInTable")
    lR.ListObject.DataBodyRange.Rows.Delete

    lCon.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=KPITRACKER;Data Source=server"
    lMonth = ThisWorkbook.Sheets("Dashboard").Shapes("dropFis_Month").ControlFormat.Value

    With lCommand
        .CommandType = adCmdStoredProc
        .CommandText = "DynamicPhonesSP"
        .Parameters.Append .CreateParameter("@TimeSum", adChar, , 1, "m")
        .Parameters.Append .CreateParameter("@TimeSum1", adChar, , 1, "d")
        .Parameters.Append .CreateParameter("@TimeParam", advarChar, , 10, lMonth)
        .Parameters.Append .CreateParameter("@RptLevel", adInteger, , , 1)
        .ActiveConnection = lCon
        Set lRecordset = .Execute
    End With

    ThisWorkbook.Sheets("Data").Range("B6").CopyFromRecordset lRecordset

    lRecordset.Close
    lCon.Close

End Sub
于 2013-11-08T23:52:27.500 回答