Я наткнулся на следующую ссылку:
http://www.informit.com/guides/content.aspx?g=sqlserver&seqNum=135
В нем они перечисляют относительно простой код для запроса базы данных SQL из 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.
Это отлично работает. Тем не менее, я хочу иметь возможность извлекать значение (я) обратно в качестве переменной, а не выводить его в Excel.
Может ли кто-нибудь помочь мне с этим? Я пытался найти Excel VBA SQL Tutorials, но кажется, что половина кода, который я нахожу, не работает (возможно, потому что я не понимаю его достаточно хорошо).