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

Posted

技术标签:

【中文标题】使用 VBA 在 Excel 中的 SQL 表上使用参数化查询【英文标题】:Using a Parameterized Query on a SQL Table in Excel using VBA 【发布时间】:2013-07-18 14:46:50 【问题描述】:

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

我用的是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

【问题讨论】:

任何帮助或建议将不胜感激! 重复的Using VBA to query a SQL Server table in Excel? 我用的是2013版的excel 谢谢!我刚刚看到我有一个“Driver=SQL Server Native Client 11.0;”而不是 10。如果您将其作为答案发布,我会接受! 【参考方案1】:

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

【讨论】:

以上是关于使用 VBA 在 Excel 中的 SQL 表上使用参数化查询的主要内容,如果未能解决你的问题,请参考以下文章

从 Excel 调用 VBA 函数 - 在选定工作表上的选定列中查找

Excel VBA 更新 SQL 表

excel多选选项列表VBA不在密码保护表上运行

[从一个单元格获取值,并将其聚焦在另一张表上,Vba Excel

如何在保存到 OneDrive 的 Excel 工作簿中运行 SQL 查询?

Excel VBA 关闭当前工作簿错误 1004