Создание параметризованных запросов SQL в Excel 2010 с VBA

StackOverflow https://stackoverflow.com/questions/4806409

Вопрос

Я наткнулся на следующую ссылку:

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, но, похоже, половина кода, которую я нахожу, не работает (возможно, потому что я не понимаю этого достаточно хорошо).

Это было полезно?

Решение

Вы можете использовать Ado, например:

''Reference: Microsft ActiveX Data Objects x.x Library
Dim cmd As New ADODB.Command
Dim cn As New ADODB.Connection
Dim param1 As New ADODB.Parameter
Dim rs As ADODB.Recordset

With cn
  .Provider = "SQLOLEDB"
  ''See also http://connectionsstrings.com
  .ConnectionString = "Data Source=Server;Initial Catalog=test;Trusted_Connection=Yes"
  .Open
End With

Set param1 = cmd.CreateParameter("@SiteID", adBigInt, adParamInput)
param1.Value = 1
cmd.Parameters.Append param1

With cmd
    .ActiveConnection = cn
    ''Stored procedure
    .CommandText = "spSiteInformation_Retrieve"
    .CommandType = adCmdStoredProc

    Set rs = .Execute
End With

For Each f In rs.Fields
  Debug.Print f.Name; " "; f
Next

rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

Дальнейшая информация: http://w3schools.com

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top