我发现了以下链接:http://www.informit.com/guides/content.aspx?g=sqlserver&seqNum=135。
其中,他们列出了相对简单的代码来查询Excel VBA中的SQL数据库。
其中,他们列出了相对简单的代码来查询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的教程,但似乎其中一半的代码都不能正常工作(可能是因为我理解不够透彻)。