2013-07-16 85 views
2

我在使用VBA在Microsoft Excel中查詢表。我已經寫了一些代碼來嘗試完成這個任務,但我不斷收到運行時錯誤「1004」,說這是一個General ODBC錯誤。我不知道我需要做什麼才能使此代碼正常運行,以便我可以查詢此表。在Excel中使用VBA查詢SQL Server中的參數化查詢

我使用的是SQL Server Express的,我連接到服務器:.\SQLEXPRESS

數據庫:

Databaselink

查詢產品表 VBA代碼:

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 

回答

2

我發現這個堆棧溢出問題與谷歌搜索。它看起來並不像任何人試圖回答它,所以這就是我最終做的。不要使用「QueryTable」,而應使用在this MSDN article中完成的ADO命令對象。

MSDN例子:

Dim Conn1 As ADODB.Connection 
Dim Cmd1 As ADODB.Command 
Dim Param1 As ADODB.Parameter 
Dim Rs1 As ADODB.Recordset 

Dim i As Integer 

' Trap any error/exception. 
On Error Resume Next 

' Create and Open Connection Object. 
Set Conn1 = New ADODB.Connection 
Conn1.ConnectionString = "DSN=Biblio;UID=admin;PWD=;" 
Conn1.Open 

' Create Command Object. 
Set Cmd1 = New ADODB.Command 
Cmd1.ActiveConnection = Conn1 
Cmd1.CommandText = "SELECT * FROM Authors WHERE AU_ID < ?" 

' Create Parameter Object. 
Set Param1 = Cmd1.CreateParameter(, adInteger, adParamInput, 5) 
Param1.Value = 5 
Cmd1.Parameters.Append Param1 
Set Param1 = Nothing 

' Open Recordset Object. 
Set Rs1 = Cmd1.Execute() 
+0

感謝張貼您的解決方案:)我一直在尋找這個你 – user1274820