0
我有一些代码应该运行查询的SQL表的参数化查询。这样做的方式是有一个指定的单元格(Z1),它应该从我的某列获取输入值,然后自动更新查询以在Excel表格中显示结果。我不断收到一个运行时错误:'1004'说这是一个通用的ODBC错误,但我不知道发生了什么。这里是我的数据库连接:Database在Excel中使用VBA在SQL表中使用参数化查询
我使用了SQL Express,所以服务器\ 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
任何帮助或建议将不胜感激! –
复制[使用VBA查询Excel中的SQL Server表](http://stackoverflow.com/questions/17656331/using-vba-to-query-a-sql-server-table-in-excel)? – jpw
我使用的是excel的2013版本 –