Excel VBA pass parameter to OLEDBConnection

2020-07-27 02:53发布

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

标签: vba excel
1条回答
贪生不怕死
2楼-- · 2020-07-27 03:30

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 & "'"
查看更多
登录 后发表回答