I am trying to query a table in Microsoft Excel using VBA. I wrote code to try to complete this task, but I get an error all the time:
'1004' runtime error: expression of a common ODBC error.
I'm not sure what I need to make this code work correctly, so I can query this table.
I am using SQL Server Express, the server I am connecting to:. .\SQLEXPRESS
Database:
Databaselink
Product table query VBA code:
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
source share