简体   繁体   中英

MS Access; Filter by Date, To & From

From a table I have created a Split Form, with two 'Date' (To and From) texts boxes with a search button.

    Private Sub btnSearch_Click()
' Search Button
Call Search
End Sub

Sub Search()
Dim strCriteria, task As String

Me.Refresh
If IsNull(Me.txtDateFrom) Or IsNull(Me.txtDateTo) Then
    MsgBox "Please enter the date range", vbInformation, "Date Range Required"
    Me.txtDateFrom.SetFocus
Else
    strCriteria = "([DateRecorded] >= #" & Me.txtDateFrom & "# And [DateRecorded] <= #" & Me.txtDateTo & "#)"
    task = "select * from tblNCRs where (" & strCriteria & ") order by [DateRecorded]"
    DoCmd.ApplyFilter task
End If

End Sub

When selecting dates and searching the code seems to work, however it is pulling up results randomly. (I believe that this is due to the code maybe using the American date format? Whereby I am using the UK Style, DD/MM/YYYY)

What can I do to make this work correctly?

Thank you

您可以使用:

strCriteria = "[DateRecorded] >= #" & Format(Me.txtDateFrom, "yyyy\/mm\/dd")  & "# And [DateRecorded] <= #" & Format(Me.txtDateTo, "yyyy\/mm\/dd") & "#"

Alternative to Gustav's answer, you could use the values on your form as parameters:

strCriteria = "[DateRecorded] >= Forms!MyFormName!txtDateFrom And [DateRecorded] <= Forms!MyFormName!txtDateTo"

This has the added advantage that when you change one of those search parameters, requerying the form is enough to work with the updated parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM