使用Excel VBA运行SQL查询

时间:2014-12-09 17:37:16

标签: sql sql-server excel vba excel-vba

我是SQL和VBA的新手。我编写了一个SQL查询,我希望能够从excel工作簿中的VBA子句调用和运行,然后将查询结果带入工作簿。我发现了一些在线(stackoverflow和其他地方)声称这样做但我无法理解它们,因为它们没有任何解释。例如,这是我在网上找到的一个子目录:

Sub ConnectSqlServer()

    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sConnString As String

    ' Create the connection string.
    sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _
                  "Initial Catalog=MyDatabaseName;" & _
                  "Integrated Security=SSPI;"

    ' Create the Connection and Recordset objects.
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset

    ' Open the connection and execute.
    conn.Open sConnString
    Set rs = conn.Execute("SELECT * FROM Table1;")

    ' Check we have data.
    If Not rs.EOF Then
        ' Transfer result.
        Sheets(1).Range("A1").CopyFromRecordset rs
    ' Close the recordset
        rs.Close
    Else
        MsgBox "Error: No records returned.", vbCritical
    End If

    ' Clean up
    If CBool(conn.State And adStateOpen) Then conn.Close
    Set conn = Nothing
    Set rs = Nothing

End Sub

首先,这会有用吗?其次,我需要在sub中替换什么(它看起来像提供者,数据源,初始目录等)以及在哪里可以找到用它们替换它们的信息?

我希望这个问题不会太令人困惑,我感谢你的帮助!

1 个答案:

答案 0 :(得分:43)

下面是我目前用于将数据从MS SQL Server 2008提取到VBA的代码。您需要确保拥有正确的ADODB参考[ VBA编辑器 - >工具 - >参考],并确保已选中 Microsoft ActiveX Data Objects 2.8 Library ,这是检查底行的第二行(我在Windows 7上使用Excel 2010;您可能会有一个稍微不同的ActiveX版本,但它仍将以Microsoft ActiveX开头):

References required for SQL

使用远程主机连接到MS SQL的子模块&用户名/密码

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub