Excel VBA pass parameter to OLEDBConnection

…衆ロ難τιáo~ 提交于 2020-02-01 07:36:20

问题


In an Excel workbook I have several connections to a SQL Server DB. I thought I could run a small script like the one below, but it's not doing what I want. I want to refresh the OLEDBConnection, and pass in a StartDate and EndDate, but it's not actually communicating with the connection.

Sub RefreshWithDates()

Dim StartDate As Date
Dim EndDate As Date

StartDate = Sheets("Pivot_Summary").Range("B1").Value
EndDate = Sheets("Pivot_Summary").Range("B2").Value

    With ActiveWorkbook.Connections("FMDDATA_HIST_SPLIT").OLEDBConnection
        .CommandText = "SELECT * FROM RECONCILIATION.dbo.TBL_FMDDATA_HIST_SPLIT Where AsOfDate between '" & StartDate & "' & " And " & '" & EndDate & "'"
        ActiveWorkbook.Connections("FMDDATA_HIST_SPLIT").Refresh
    End With

End Sub

回答1:


Your .CommandText string has an error around the AND (notice how it is blue in color... it is resolving as the VBA keyword And).

It should read:

"EXEC SELECT * FROM RECONCILIATION.dbo.TBL_FMDDATA_HIST_SPLIT 
WHERE AsOfDate between '" & StartDate & "'" & " AND " & "'" & EndDate & "'"


来源:https://stackoverflow.com/questions/50722443/excel-vba-pass-parameter-to-oledbconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!