2013-07-12 2 views
1

아래는 Excel에서 매개 변수화 된 쿼리를 작성해야하는 코드입니다. MS Excel 2013을 실행 중입니다. 현재 SQL Server 데이터베이스에 연결하려고합니다. 여기에서 필자는 열 값을 입력하고 열의 모든 행 (WHERE 절)에 대해 데이터베이스를 쿼리하는 단일 셀을 사용하여이 데이터베이스를 쿼리하려고합니다. 이 셀은 동적이기 때문에 값을 변경하면 쿼리의 결과가 변경됩니다. 때 .refresh 섹션에서VBA를 사용하는 매개 변수로 Excel에서 테이블 쿼리

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

내가 오류가 계속 : 저는 여기에서

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 

이 코드입니다. 누구든지 도와 줄 수 있습니까? 다음은 내 DB에 대한 링크입니다 Database link

SQL Server Express를 실행하고 서버는. \ SQLEXPRESS입니다. 누구든지 도움을받을 수 있다면 크게 감사하겠습니다.

+0

어떤 오류가 발생합니까? 런타임 오류 '1004': 일반 ODBC 오류 내가 최근에 비슷한 일을 시도했습니다 –

+0

나는이 오류가 계속 '티. –

+0

과'Add' didn를 어디에, Paramterer.Append' 근무''CreateParameter'를 사용하고 있음을 발견 –

답변

0

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는

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') 

것은해야 ... 다음 코드를 사용하여 단 몇 행을 포함하는 DimCurrency 테이블의 미니 버전으로 데이터베이스를 만들 수 있습니다 설치 스프레드 시트 매개 변수를 기반으로 동적 쿼리를 만들려는 경우 유일한 옵션 인 것처럼 보이는 ODBC 드라이버를 사용하십시오. OLE DB 드라이버를 사용할 수 없다고 생각합니다. 나는 언젠가 누군가가 나를 틀리게 증명할 것을 희망한다.

결과가 없습니다. USD (EUR 또는 SEK)을 A1 셀에 넣으면 쿼리가 자동으로 업데이트됩니다.

관련 문제