VBA 过程中 Microsoft Access SQL Select 查询中的语法错误

Syntax error in Microsoft Access SQL Select query in VBA procedure

我有以下 VBA 代码出现语法错误。有人可以帮我找出导致错误的原因吗?

Private Sub Command11_Click()
    Dim EndingDate As Date
    'Getting ending date from Label named endDate
    EndingDate = endDate
    StartingDateTxt = DateSerial(Year(EndingDate), Month(EndingDate) - 15, Day(EndingDate))

    Dim customerRecords As New ADODB.Recordset
    customerRecords.Open "SELECT COUNT(*) AS N FROM (SELECT   DISTINCT E.Date,"&_
                        "E.[Inv Num],   E.CusName, E.[Name Street1], E.[Name Street2], "&_
                        "E.[Name City], E.[Name State], E.[Name Zip], E.[Account #], E.Amount FROM TempFromExcel "&_
                        "AS E  INNER JOIN TempFromExcel AS X ON E.CusName = X.CusName "&_
                        "WHERE (((DateDiff("d",X.Date,E.Date))>=30))  AND E.Date >= '" & StartingDateTxt & "' and"&_
                        "E.Date <= '" & endDate & "') AS T ;", _
                 CodeProject.Connection , _
                 adOpenStatic, _
                 adLockOptimistic, _
                 adCmdText
    MsgBox customerRecords("N")

End Sub

我的查询使用两个日期并查找两个日期之间的结果。

我想我可能只漏掉了那部分。其余的似乎很好,因为我已经明确检查了查询并且它运行良好。那么这样对吗?

E.Date >= '" & StartingDateTxt & "' and E.Date <= '" & endDate & "'

这已在答案中更正,但在 Select 语句第一行中仍然出现语法错误。是不是漏了什么?

在 Microsoft Access SQL 查询中,您必须将日期值封装到 ## 中,例如 #06/01/2015#。与您的情况相关,它应该如下所示:

E.Date >= #" & StartingDateTxt & "# AND E.Date <=#" & endDate & "#"

希望这可能有所帮助。

尝试更改这些行:

"WHERE (DateDiff('d', X.Date, E.Date) >= 30 AND E.Date >= #" & Format(StartingDateTxt, "yyyy\/mm\/dd") & "# and " & _
"E.Date <= #" & Format(endDate, "yyyy\/mm\/dd") & "#) AS T ;", _