Marc
Marc

Reputation: 16512

Issue comparing dates with the same format

I'm trying to filter a form with a interval of time

the start date and end date are both in a textbox with this format dd/mm/yyyy

My query in VBA looks like this

WHERE (Format([SalesCallDate],'dd/mm/yyyy') BETWEEN #" & Format(txtStartDate, "dd/mm/yyyy") & "#
 AND #" & Format(txtEndDate, "dd/mm/yyyy") & "#)"

I can't figure out why when the interval is 01/12/2012 to 21/12/2012, I got dates like 15/08/1991. That's why I wanted to be explicit with the format.

the output for the SQL query is
WHERE (Format([SalesCallDate],'dd/mm/yyyy') BETWEEN #01/12/2012# AND #21/12/2012#)

I tried with and without the format.

Am I missing something?

NOTE: SalesCallDate is a DateTime field in a SQL Server linked table

Thank you

Upvotes: 2

Views: 1048

Answers (1)

HansUp
HansUp

Reputation: 97101

It sounds like txtStartDate and txtEndDate are both unbound text boxes. Set their format properties to a date format.

text box with Format set to General Date

With a date format and the "Show Date Picker" property set to "For dates", Access versions >= 2007 will enable that date picker feature for your text boxes. If your users like that, this is a side benefit of that format property.

Anyway the date format will allow Access and VBA to interpret those text box values as Date/Time data type:

? TypeName(Forms!frmDateRange!txtStartDate.Value)
Date

Then since SalesCallDate is Date/Time type, your WHERE clause can compare the field directly to the text box values.

WHERE SalesCallDate BETWEEN
        Forms!frmDateRange!txtStartDate
    AND Forms!frmDateRange!txtEndDate

Or if your form has code which builds a string containing your SQL statement, and you want Date/Time literals for the date range ...

"WHERE SalesCallDate BETWEEN " & _
    Format(Me.txtStartDate, "\#yyyy-m-d\#")
    " AND " & Format(Me.txtEndDate, "\#yyyy-m-d\#")

Upvotes: 1

Related Questions