Excel的ADODB连接中GO附近的语法错误

时间:2013-11-08 23:22:41

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

我正在尝试将带有存储过程的SQLServer数据库中的数据直接导入和退出电子表格。我正在尝试创建一个仪表板,允许用户选择他们想要查看的特定月份并提取该月的数据。拉动数据后,仪表板将自动计算用户将看到的图表等等。这是我第一次从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

1 个答案:

答案 0 :(得分: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