Search code examples
sqlms-accessvbasubqueryselect-query

Syntax error in Microsoft Access SQL Select query in VBA procedure


I am having following VBA Code that has been giving a syntax error. Can someone please help me figure out what is causing the error?

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

My Query is taking both dates and finding the results that are between the two dates.

I think I may be missing at that part only. The rest seems fine as I had explicitly check the query and it runs fine. So is this right ?

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

This has been corrected, in the answer but still am getting syntax error in Select statement first line. Am missing something?


Solution

  • Try changing these lines:

    "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 ;", _