Question

I have some code that is supposed to run a parameterized query of the SQL table that I am query. The way that it does this is there is a designated cell (Z1) that is supposed to take in an input value from one of my columns and then automatically update the query to display the results in the excel table. I keep getting a run-time error: '1004' which says it's a General ODBC error, but I'm not sure what is happening. Here is the database that I am connection to: Database

I'm using SQL express, so the server is .\SQLEXPRESS

Here is the code that I have:

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
Was it helpful?

Solution

Open up the ODBC Data Source Admin program in Control Panel\System and Security\Administrative Tools and check that the driver you specified in the code "Driver={SQL Server Native Client 10.0};" matches a driver under the Drivers tab. A mismatch can give this error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top