gpt4 book ai didi

sql - 使用 VBA 在 Excel 中查询 SQL Server 表

转载 作者:行者123 更新时间:2023-12-02 12:16:39 26 4
gpt4 key购买 nike

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

run-time error '1004': Saying it's a General ODBC error.

我不确定需要做什么才能使此代码正常运行,以便我可以查询此表。

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

最佳答案

执行此操作的解决方案是下一个

Dim lo As ListObject
Set lo = ActiveSheet.ListObjects.Add(xlSrcExternal, _
"OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=SERVER_NAME;Data Source=CONNECTION_ADRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False", _
True, xlYes, Range("A2"))

lo.QueryTable.CommandType = xlCmdSql
lo.QueryTable.CommandText = "SELECT * FROM TABLE_NAME"

With lo.QueryTable.Parameters.Add("Currency code", xlParamTypeVarChar)
.SetParam xlRange, ActiveSheet.Range("A1")
.RefreshOnChange = True
End With

lo.QueryTable.Refresh BackgroundQuery:=False

您可以通过 SQL 查询创建一个 listObject。

关于sql - 使用 VBA 在 Excel 中查询 SQL Server 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17656331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com