Sql server 使用VBA在Excel中的SQL表上使用参数化查询

Sql server 使用VBA在Excel中的SQL表上使用参数化查询,sql-server,excel,vba,parameterized-query,Sql Server,Excel,Vba,Parameterized Query,我有一些代码,应该运行我正在查询的SQL表的参数化查询。这样做的方式是有一个指定的单元格(Z1),它应该从我的一列中获取输入值,然后自动更新查询以在excel表中显示结果。我一直收到一个运行时错误:“1004”表示这是一个一般的ODBC错误,但我不确定发生了什么。以下是我连接到的数据库: 我正在使用SQL express,因此服务器是。\SQLEXPRESS 以下是我的代码: Sub ParameterQueryExample() '---creates a ListObject-QueryTa

我有一些代码,应该运行我正在查询的SQL表的参数化查询。这样做的方式是有一个指定的单元格(Z1),它应该从我的一列中获取输入值,然后自动更新查询以在excel表中显示结果。我一直收到一个运行时错误:“1004”表示这是一个一般的ODBC错误,但我不确定发生了什么。以下是我连接到的数据库:

我正在使用SQL express,因此服务器是。\SQLEXPRESS

以下是我的代码:

Sub ParameterQueryExample()
'---creates a ListObject-QueryTable on Sheet1 that uses the value in 
'        Cell Z1 as the ProductID Parameter for an SQL Query
'        Once created, the query will refresh upon changes to Z1. 

Dim sSQL As String
Dim qt As QueryTable
Dim rDest As Range


'--build connection string-must use ODBC to allow parameters
Const sConnect = "ODBC;" & _
    "Driver={SQL Server Native Client 10.0};" & _
    "Server=.\SQLEXPRESS;" & _
    "Database=TSQL2012;" & _
    "Trusted_Connection=yes"


'--build SQL statement
sSQL = "SELECT *" & _
        " FROM TSQL2012.Production.Products Products" & _
        " WHERE Products.productid = ?;"


'--create ListObject and get QueryTable
Set rDest = Sheets("Sheet1").Range("A1")
rDest.CurrentRegion.Clear  'optional- delete existing table


Set qt = rDest.Parent.ListObjects.Add(SourceType:=xlSrcExternal, _
    Source:=Array(sConnect), Destination:=rDest).QueryTable


'--add Parameter to QueryTable-use Cell Z1 as parameter
With qt.Parameters.Add("ProductID", xlParamTypeVarChar)
    .SetParam xlRange, Sheets("Sheet1").Range("Z1")
    .RefreshOnChange = True
End With


'--populate QueryTable
With qt
    .CommandText = sSQL
    .CommandType = xlCmdSql
    .AdjustColumnWidth = True  'add any other table properties here
    .BackgroundQuery = False
    .Refresh
End With


Set qt = Nothing
Set rDest = Nothing
End Sub

在“控制面板\系统和安全\管理工具”中打开ODBC数据源管理程序,并检查在“驱动程序={SQL Server Native Client 10.0};”“中指定的驱动程序是否与“驱动程序”选项卡下的驱动程序匹配。不匹配可能导致此错误。

如有任何帮助或建议,将不胜感激!的副本?我使用的是2013版的Excel谢谢!我刚刚看到我有一个“Driver={SQLServer原生客户端11.0};”而不是10。如果你把它作为一个答案,我会接受它!