4
我在使用VBA在Microsoft Excel中查询表格。我已经写了一些代码,试图完成这个任务,但我不断收到一个错误:使用VBA查询Excel中的SQL Server表格
run-time error '1004': Saying it's a General ODBC error.
我不知道我需要做的就是这个代码正常运行,所以我可以查询此表。
我使用的是SQL Server Express的,我连接到服务器:.\SQLEXPRESS
数据库:
查询产品表 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
看看这里:[http://www.connectionstrings.com/sql-server/](http://www.connectionstrings.com/sql-server/)。有几种方法可以连接到sql server和少数提供者...尝试不同的连接设置。 –
在哪_line_上发生这种情况?给我们一个线索。 –