Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

[SQL Server][Access VBA][ADO] using date/time criteria in a query

Status
Not open for further replies.

KevTheKiwi

IS-IT--Management
Joined
May 6, 2002
Messages
1
Location
AU
This problem gave me a whole bunch of hassle, so I thought I'd post my solution as it cost me a half day of browsing the ng's

If you're trying to execute an SQL query on SQL Server via MS Access/VBA/ADO/OLEDB that has a date criteria, e.g.

Code:
WHERE AND [table name].[date field]>=#03/04/2002# And [table name].[date field]<=#23/09/2002#

you'll find that the above will execute fine in a jet query to over linked tables, but won't execute via ADO/VBA. You'll probably get error codes and messages like:

Code:
-2147217913 The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value.

OR:

Code:
-2147217900 Line 1: Incorrect syntax near '#'

The first error with the 'smalldatetime' will come up if you try and use single quotes to delimit the date value in the SQL string e.g.

Code:
&quot;WHERE AND [table name].[date field]>='&quot; & CStr(DateValue([from date variable])) & &quot;' And [table name].[date field]<='&quot; & CStr(DateValue([from date variable])) & &quot;'&quot;

The second error will come up if you try to use the hash '#' as a value delimiter much as you do in a standard jet query created via a wizard or whatever

Anyways, the following works a treat:

Code:
&quot;WHERE [table name].[date field] BETWEEN '&quot; & _
Format(CStr(datFromDate), &quot;mm/dd/yyyy&quot;) & &quot;' And '&quot; & _
Format(CStr(datToDate), &quot;mm/dd/yyyy&quot;) & &quot;' &quot;

where datFromDate and datToDate are the date range you need the criteria to match. ignore any newsgroup comments you may get about a date in the data being not a valid date value or outside some 2097 or 1701 or other rubbish year value, they're just red herrings. I found DateValue() was good for stripping the 'xx:xx:xx PM' time values at the end of the Date string that ActiveX control date pickers seem to like to give you and which VBA will seem to mysteriously and intermittently append if you pass two or more Date variables as sub or function arguments.

HTH

ktk
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top