使用VBA使用参数查询Excel中的表

时间:2013-07-12 15:45:34

标签: sql excel vba parameterized-query

以下是我在Excel中创建参数化查询的代码。我正在运行MS Excel 2013.我正在做的是尝试连接到SQL Server数据库。从这里开始,我想使用单个单元格查询此数据库,您可以在其中键入列的值,并在数据库中查询该列中的所有行(WHERE子句)。此单元格应该是动态的,因此当您更改其中的值时,它会更改查询的结果。这是我的代码

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部分继续收到错误。有人可以帮忙吗?这是我的数据库 Database link

的链接

我正在运行SQL Server Express,服务器是。\ SQLEXPRESS。如果有人能提供帮助,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

针对AdventureWorksDW2012生成动态参数化查询的VBA代码。

将参数(例如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,您可以使用以下代码创建包含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驱动程序,因为如果要基于电子表格参数创建动态查询,它似乎是唯一的选项。我不认为可以使用OLE DB驱动程序。但是,我希望有一天有人会证明我是错的。

没有结果?请务必将USDEURSEK)放入单元格A1中,查询将自动更新。