gpt4 book ai didi

sql-server - 使用 VBA 通过参数化查询在 Excel 中查询 SQL Server

转载 作者:行者123 更新时间:2023-12-03 02:54:10 25 4
gpt4 key购买 nike

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


'--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

最佳答案

我通过 Google 搜索发现了这个 Stack Overflow 问题。看起来没有人尝试回答这个问题,所以这就是我最终所做的。不要使用“QueryTable”,而是使用 ADO 命令对象,如 this MSDN article 中所做的那样。 .

MSDN 示例:

Dim Conn1 As ADODB.Connection
Dim Cmd1 As ADODB.Command
Dim Param1 As ADODB.Parameter
Dim Rs1 As ADODB.Recordset

Dim i As Integer

' Trap any error/exception.
On Error Resume Next

' Create and Open Connection Object.
Set Conn1 = New ADODB.Connection
Conn1.ConnectionString = "DSN=Biblio;UID=admin;PWD=;"
Conn1.Open

' Create Command Object.
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = Conn1
Cmd1.CommandText = "SELECT * FROM Authors WHERE AU_ID < ?"

' Create Parameter Object.
Set Param1 = Cmd1.CreateParameter(, adInteger, adParamInput, 5)
Param1.Value = 5
Cmd1.Parameters.Append Param1
Set Param1 = Nothing

' Open Recordset Object.
Set Rs1 = Cmd1.Execute()

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

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