使用VBA在Excel中查询SQL Server表

我想使用VBA在Microsoft Excel中查询表格。 我已经写了一些代码来尝试完成这个任务,但我不断收到一个错误:

运行时错误'1004':说这是一个通用的ODBC错误。

我不知道我需要做什么才能让这个代码正常运行,所以我可以查询这个表。

我正在使用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 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 

使用OLEDB提供程序的Excel,它应该工作正常。