在Excel中使用VBA查询参数

以下是我必须在Excel中创build参数化查询的代码。 我正在运行MS Excel 2013.我正在做的是试图连接到SQL Server数据库。 从这里我想查询这个数据库使用单个单元格,您键入一列的值,并查询数据库中该列(WHERE子句)的所有行。 这个单元格应该是dynamic的,所以当你改变它的值的时候,它会改变查询的结果。 这是我有的代码

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 

在:

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

我一直在.Refresh部分收到一个错误。 谁能帮忙? 这是一个链接到我的数据库数据库链接

我正在运行SQL Server Express,服务器是\ SQLEXPRESS。 如果任何人都可以帮助,将不胜感激。

VBA代码,用于根据AdventureWorksDW2012生成dynamic参数化查询。

将参数,例如USD ,放在单元格A1中。

 Sub DynamicParameterizedQuery() Dim lo As ListObject Set lo = ActiveSheet.ListObjects.Add(xlSrcExternal, "ODBC;Driver={SQL Server Native Client 11.0};Server=.;Database=AdventureWorksDW2012;Trusted_Connection=yes", True, xlYes, Range("A2")) lo.QueryTable.CommandType = xlCmdSql lo.QueryTable.CommandText = "SELECT * FROM DimCurrency WHERE CurrencyAlternateKey = ?" With lo.QueryTable.Parameters.Add("Currency code", xlParamTypeVarChar) .SetParam xlRange, ActiveSheet.Range("A1") .RefreshOnChange = True End With lo.QueryTable.Refresh BackgroundQuery:=False End Sub 

如果没有安装AdventureWorksDW2012,则可以使用以下代码创build数据库,其中包含仅包含几行的DimCurrency表的迷你版本…

 USE master GO CREATE DATABASE AdventureWorksDW2012 GO USE AdventureWorksDW2012 CREATE TABLE DimCurrency( CurrencyKey int NOT NULL, CurrencyAlternateKey nchar(3) NOT NULL, CurrencyName nvarchar(50) NOT NULL ) INSERT INTO DimCurrency VALUES (36, 'EUR', 'EURO'), (100, 'USD', 'US Dollar'), (91, 'SEK', 'Swedish Krona') 

确保使用ODBC驱动程序,因为如果您想要基于电子表格参数创builddynamic查询,则它似乎是唯一的select。 我不认为有可能使用OLE DB驱动程序。 但是,我希望有一天有人会certificate我错了。

没有结果? 请记住在USDEURSEK )在单元格A1和查询将自动更新。