Excel外部数据联合查询中的参数

时间:2017-08-16 19:43:05

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

我有两个查询将数据从SQL Server提取到Excel中。两者都完美无缺。我试图将它们联合在一起并传递参数作为日期,现在没有任何作用。这是一篇描述如何使用Microsoft Query并传入参数的文章的链接。

http://dailydoseofexcel.com/archives/2004/12/13/parameters-in-excel-external-data-queries/

我想要做的就是使用Union Query。那可能吗?或者,我是否需要VBA解决方案才能实现此目的。我确信它是可行的,我只是不知道该怎么做。我很感激任何建议。

谢谢!

1 个答案:

答案 0 :(得分:0)

谢谢大家。我最终在VBA中做到了。

Sub ImportFromDB()

' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection

' Provide the connection string.
Dim strConn As String

'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"

'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=SERVER_NAME;INITIAL CATALOG=Data_Base;"

'Use an integrated login.
strConn = strConn & "Trusted_Connection=Yes;"

'Now open the connection.
cnPubs.Open strConn

' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
Set sht = Worksheets("Impact Analysis")

    With sht
        .Range("N:U").ClearContents
        .Range("N1").Resize(1, 8).Value = Array("CONTACT_ID", "CATEGORY", "COMPANY_CODE", "CUSTOMER_NO", "SECTOR", "DES", "ASOFDATE", "BALANCE")
        Set rw = .Rows(2)
    End With

    With rsPubs
        ' Assign the Connection object.
        .ActiveConnection = cnPubs
        ' Extract the required records.
        .Open "SELECT * FROM MY_TABLE"

        ' Copy the records into cell A1 on Sheet1.
        Worksheets("Impact Analysis").Range("N2").CopyFromRecordset rsPubs

        ' Tidy up
        .Close
    End With

cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing

End Sub