I have the following vba query that works fine if there are no blank records in a particular field that contains dates. The error occurs when a blank exists in a particular record.
What am I trying to do?: extract a count out of my database between a date range. The startdate and enddate are cell references formatted as "MM/DD/YYYY" and the datebase field containing the dates are formatted as Date/Time, "short date".
query that works if my field column doesnt contain any blanks:
Dim startdate As Date
Dim enddate As Date
strSql = "SELECT Count(*) FROM tablename WHERE datevalue(Date_field_name) >= " & Format(startdate, "\#mm-dd-yyyy\#") & "AND datevalue(Date_field_name) <= " & Format(enddate, "\#mm-dd-yyyy\#")
I tried adding IS NOT NULL and that doesnt work:(
strSql = "SELECT Count(*) FROM tablename WHERE ANOTHER_Field_Name IS NOT NULL AND datevalue(Date_field_name) >= " & Format(startdate, "\#mm-dd-yyyy\#") & "AND datevalue(Date_field_name) <= " & Format(enddate, "\#mm-dd-yyyy\#")
help me pls!! This is driving me mad.
EDIT The complete code:
Public Sub counter()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim myCounter As Variant
Dim startdate As Date
Dim enddate As Date
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=Data.mdb"
strSql = "SELECT Count(*) FROM tablename WHERE datevalue(Date_field_name) >= " & Format(startdate, "\#mm-dd-yyyy\#") & "AND datevalue(Date_field_name) <= " & Format(enddate, "\#mm-dd-yyyy\#")
cn.Open strConnection
'Set rs = cn.Execute(strSql)
While (rs.EOF = False)
If (Not IsNull(rs(Sent_To_Tech_Date).Value)) Then
myCounter = myCounter + 1
End If
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub