Hi All, if anyone could help me with my codes. I have a form with txtStartDate, txtEndDate, with a listbox lstWorkSLY and a cmdRunExtract button. I wanted to query records filtering txtStartDate to txtEndDate based on the items selected in lstWorkSLY. Here's my code, it is not working when I set Nov. 5, 2008 as my txtStartDate and Nov. 28, 2008 as my txtEndDate still all records with DateX June 1, 2008 to January 2009 appears as my output. I don't know where to place my date range condition. Please help me! Thanks in advance.
Code:
Private Sub cmdRunExtract_click()
On Error GoTo Err_cmdRunExtract_click
Dim db As Database
Dim qdef As QueryDef
Dim i As Integer
Dim strSQL As String
Dim strWhere As String
Dim strIN As String
Dim flgSelectAll As Boolean
Dim varItem As Variant
Dim strDateField As String
Dim strWhereDate As String
Const strcJetDate = "\#mm\/dd\/yyyy\#" 'do not change it to much your local settings
Set db = CurrentDb()
strSQL = "select * from tblSLY"
strDateField = "[DateX]" 'date field from table tblSLY
'Build the filter string
If IsDate(Me.txtStartDate) Then
strWhereDate = "(" & strDateField & ">= " & Format(Me.txtStartDate, strcJetDate) & ")"
End If
If IsDate(Me.txtEndDate) Then
If strWhereDate <> vbNullString Then
strWhereDate = strWhereDate & " and "
End If
strWhereDate = strWhereDate & "(" & strDateField & " < " & Format(Me.txtEndDate + 1, strcJetDate) & ")"
'end if
'build the IN string by looping through the list
For i = 0 To lstWorkSIMMSLY.ListCount - 1
If lstWorkSLY.Selected(i) Then
If lstWorkSLY.Column(0, i) = "All" Then
flgSelectAll = True
End If
strIN = strIN & "'" & lstWorkSLY.Column(0, i) & "',"
End If
Next i
'Create the WHERE string, and strip off the last comma of the IN string
strWhere = " where [Natr] in " & _
"(" & Left(strIN, Len(strIN) - 1) & ")"
'if ALL was selected in the listbox, don't add the WHERE condition
If Not flgSelectAll Then
strSQL = strSQL & strWhere
End If
End If
db.QueryDefs.Delete "qrySLY"
Set qdef = db.CreateQueryDef("qrySLY", strSQL)
'Open the query, built using the In clause to set the criteria
DoCmd.OpenQuery "qrySLY", acViewNormal
'Clear listbox selection after running query
For Each varItem In Me.lstWorkSLY.ItemsSelected
Me.lstWorkSLY.Selected(varItem) = False
Next varItem
exit_cmdRunExtract_click:
Exit Sub
Err_cmdRunExtract_click:
If Err.Number = 5 Then
MsgBox "You must make a selection(s) from the list", , "Selection Required!"
Resume exit_cmdRunExtract_click
Else
'Write out the error and exit the sub
MsgBox Err.Description
Resume exit_cmdRunExtract_click
End If
End Sub
Comment