2013-07-18 2 views
0

나는 쿼리하는 SQL 테이블의 매개 변수화 된 쿼리를 실행하기로되어있는 코드가 있습니다. 이 방법은 내 열 중 하나에서 입력 값을 가져와 Excel 테이블에 결과를 표시하도록 쿼리를 자동으로 업데이트하는 지정된 셀 (Z1)이 있습니다. 계속 런타임 오류가 발생합니다 : '1004'는 일반 ODBC 오류라고하지만, 어떤 일이 일어나고 있는지 잘 모르겠습니다. 저는 여기에 연결 오전 데이터베이스입니다 : DatabaseVBA를 사용하여 Excel에서 SQL 테이블의 매개 변수화 된 쿼리 사용

것은 내가 SQL 익스프레스를 사용하고, 그래서 서버는 \ 여기

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 
+0

도움이나 의견을 보내 주시면 대단히 감사하겠습니다. –

+0

[VBA를 사용하여 Excel에서 SQL Server 테이블 쿼리하기] (http://stackoverflow.com/questions/17656331/using-vba-to-query-a-sql-server-table-in-excel)? – jpw

+0

2013 버전의 Excel을 사용 중입니다. –

답변

1

가 열기는 제어판 \ 시스템 및 보안 \ 관리 도구의 ODBC 데이터 원본 관리 프로그램을 열고 코드 "Driver={SQL Server Native Client 10.0};"에 지정한 드라이버가 드라이버 탭의 드라이버와 일치하는지 확인하십시오. 일치하지 않으면이 오류가 발생할 수 있습니다.

관련 문제