使用 VBA 在 Excel 2010 中创建参数化 SQL 查询
我发现了以下链接:
http://www.informit。 com/guides/content.aspx?g=sqlserver&seqNum=135
在其中,他们列出了从 Excel VBA 查询 SQL 数据库的相对简单的代码。
' Declare the QueryTable object
Dim qt As QueryTable
' Set up the SQL Statement
sqlstring = "select au_fname, au_lname from authors"
' Set up the connection string, reference an ODBC connection
' There are several ways to do this
' Leave the name and password blank for NT authentication
connstring = _
"ODBC;DSN=pubs;UID=;PWD=;Database=pubs"
' Now implement the connection, run the query, and add
' the results to the spreadsheet starting at row A1
With ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("A1"), Sql:=sqlstring)
.Refresh
End With
'Save and close the macro, and run it from the same menu you accessed in step 2.
这很好用。但是,我希望能够将值作为变量拉回,而不是将其转储到 Excel。
有人可以帮我吗?我尝试过寻找 Excel VBA SQL 教程,但似乎我找到的一半代码不起作用(可能是因为我对它的理解不够好)。
I came across the following link:
http://www.informit.com/guides/content.aspx?g=sqlserver&seqNum=135
In it, they list relatively simple code to query the SQL Database from Excel VBA.
' Declare the QueryTable object
Dim qt As QueryTable
' Set up the SQL Statement
sqlstring = "select au_fname, au_lname from authors"
' Set up the connection string, reference an ODBC connection
' There are several ways to do this
' Leave the name and password blank for NT authentication
connstring = _
"ODBC;DSN=pubs;UID=;PWD=;Database=pubs"
' Now implement the connection, run the query, and add
' the results to the spreadsheet starting at row A1
With ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("A1"), Sql:=sqlstring)
.Refresh
End With
'Save and close the macro, and run it from the same menu you accessed in step 2.
This works fine. However, I want to be able to pull a value(s) back as a variable instead of dumping it to Excel.
Can someone assist me with that? I've tried looking for Excel VBA SQL Tutorials, but it seems that half the code I find doesn't work (perhaps because I don't understand it well enough).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 ADO,例如:
更多信息:http://w3schools.com
You can use ADO, for example:
Further information: http://w3schools.com