VBA 尝试 运行 两个日期之间的 SQL 查询时出现问题

VBA issues when trying to run a SQL query between 2 dates

为了简要总结这个宏的 objective,我试图根据一组参数获取特定日期之间的现金总和。当我尝试 运行 带有日期的 SQL 查询时,我总是在 VBA 中收到错误。我不确定问题出在哪里,但我认为这与我设置日期格式的方式有关。我尝试了 运行 多种方式,但总是出现语法错误,无论它与 'a'、'#' 还是 'table'.

有关

这是我正在使用的查询。任何帮助将不胜感激。

Sub GetCashBalance()

Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim SQL As String
Dim StartDate As String
Dim EndDate As String

StartDate = InputBox("Enter Start Date in mm/dd/yy format.")
EndDate = InputBox("Enter End Date in mm/dd/yy format.")

SQL = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=master;Data Source=SERVER\ODS"

Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset

cn.Open SQL
Set rs = cn.Execute("SELECT SUM(a.CASH)" & _
            "FROM CUSTOMER_DATA.dbo.TRANSACTION_HISTORY a" & _
            "LEFT JOIN CUSTOMER_DATA.dbo.DAILY_TRANSACTION b" & _
            "ON a.T01_KEY = b.T01_KEY" & _
            "WHERE PROC_DATE BETWEEN #StartDate# AND #EndDate#" & _
            "AND a.CODE NOT IN ('22','23','M','2-L','36-R')" & _
            "AND isnull(a.DESCRIPTION, '') NOT IN ('01','02','03','0DO1','0NF2');")

If Not rs.EOF Then
    Sheets(7).Range("A40").CopyFromRecordset rs
    rs.Close
Else
    MsgBox "Error", vbCritical
End If

cn.Close

End Sub
Set rs = cn.Execute("SELECT SUM(a.CASH)" & _
            "FROM CUSTOMER_DATA.dbo.TRANSACTION_HISTORY a" & _
            "LEFT JOIN CUSTOMER_DATA.dbo.DAILY_TRANSACTION b" & _
            "ON a.T01_KEY = b.T01_KEY" & _
            "WHERE PROC_DATE BETWEEN '" & StartDate & "' AND '" & EndDate & _
            "# AND a.CODE NOT IN ('22','23','M','2-L','36-R')" & _
            "AND isnull(a.DESCRIPTION, '') NOT IN ('01','02','03','0DO1','0NF2');")

看看下面这块,应该改一下

BETWEEN '" & StartDate & "' AND '" & EndDate & _            
"' AND ....

我认为最好使用 ADODB.CommandParameters 而不是在 sql 查询中进行串联。