0

如何编写 VBA 宏以在 MS SQL Server 2008 数据库上运行 SQL 查询,并将结果输出到电子表格中?

4

1 回答 1

1
  1. 打开 Excel,然后打开宏编辑器 (Alt + F11)
  2. 转到工具> 参考并添加最新安装的 Microsoft ActiveX 数据对象 XX 库版本(在我的情况下为 6.1)
  3. 添加一个新的Sub如下
Sub RunSQL(sConnectionString, sSqlQuery, sWorkSheet, nStartColumn, nStartRow)

    Dim oConnection As New ADODB.Connection
    Dim oRecordSet As New ADODB.Recordset
    Dim sQuery As String
    Dim intMaxCol As Integer
    Dim intMaxRow As Integer

    'Connection to SQL Server
    Call oConnection.Open(sConnectionString)

    ' Get Recordset
    Call oRecordSet.Open(sSqlQuery, oConnection, adOpenStatic, adLockReadOnly)

    ' Get SQL Query Column Count
    intMaxCol = oRecordSet.Fields.Count
    If oRecordSet.RecordCount > 0 Then

        ' Get SQL Query Row Count
        intMaxRow = oRecordSet.RecordCount

        ' Paste data into sheet
        Call Worksheets(sWorkSheet).Range(Worksheets(sWorkSheet).Cells(nStartRow, nStartColumn), Worksheets(sWorkSheet).Cells(intMaxRow + nStartRow, intMaxCol + nStartColumn)).CopyFromRecordset (oRecordSet)

    End If

    ' Close objects
    oRecordSet.Close
    oConnection.Close
End Sub
  1. 从您的代码中调用它,更新参数如下:
Call RunSQL("Provider=SQLNCLI10;Server=[[SERVER]]\[[INSTANCE]];Database=[[DATABASE]];Trusted_Connection=Yes;", _
         "SELECT TOP 1 CAST(UniqueId AS VARCHAR(40)), Name FROM Employee WITH (NOLOCK)", _
         "Sheet1", _
         2, _
         3)

如果有帮助,我是从涉及以下帖子的蜿蜒路线中得到的:

于 2013-10-28T16:20:16.420 回答