Opening a Report based on two date values on a form if they exist - vba

I have a form (frmReports) that has two unbound textboxes which are used to enter dates. One is FROM, one is TO.
These are used to filter out a report (rptAllCommissions). If there are values in the textboxes, it filters. If there aren't, or if there's one date and not both, it creates a WHERE statement for opening the report. Here is the code:
Private Sub cmdCommissions_Click()
Dim strDateFrom As String
Dim strDateTo As String
Dim strWhere As String
Const strcJetDate = "\#mm\/dd\/yyyy\#"
strDateFrom = "[ClosingDate]"
If IsDate(Me.txtFrom) Then
strWhere = "(" & strDateFrom & " >=" & Format(Me.txtFrom, strcJetDate) & ")"
End If
If IsDate(Me.txtTo) Then
If strWhere <> vbNullString Then
strWhere = strWhere & " AND "
End If
strWhere = strWhere & "(" & strDateFrom & " <= " & Format(Me.txtTo + 1, strcJetDate) & ")"
End If
If CurrentProject.AllReports("rptAllCommissions").IsLoaded Then
DoCmd.Close acReport, "rptAllCommissions"
End If
Debug.Print strWhere
DoCmd.OpenReport "rptAllCommissions", acViewReport, strWhere
Exit_Handler:
Exit Sub
Err_Handler:
If Err.Number <> 2501 Then
MsgBox "Error" & Err.Number & ": " & Err.Description, vbExclamation, "Cannot Open Report!"
End If
Resume Exit_Handler
End Sub
The problem I'm having is no matter what I try, the report never filters the records based on the WHERE statement created by the above routine. Trying debugging, it outputs:
If two dates are entered: ([ClosingDate] >=#04/01/2019#) AND ([ClosingDate] <= #05/25/2019#)
If one date is entered: ([ClosingDate] >=#05/13/2019#)
That seems right to me, but it's not filtering. What the heck am I doing wrong?
EDIT: I should give credit the person who wrote the original routine, but I can't for the life of me find where I got it. Sorry! But whoever it was that originally wrote the routine, THANKS!

The WhereCondition should be the 4th argument in the OpenReport method. You have it in the FilterName argument's spot.
OpenReport

Related

Filter form records by date range using two unbound text boxes

Good afternoon.
I have a continuous form which I want to allow the user to filter by using unbound boxes in the form header. See screenshot of form below:
Form Design View
I can filter error type (Unbound: cboErrorType) and responsibility (Unbound: cboResponsibility) without any issues, but I cannot get the date range to work (Records outside of the selected date range are being returned). Please see screenshot:
Form - filtered
Please see my code below:
Private Sub cmdFilter_Click()
Dim strWhere As String
Dim lngLen As Long
Const conJetDate = "\#dd\/mm\/yyyy\#"
If Not IsNull(Me.cboErrorType) Then
strWhere = strWhere & "([ErrorType] = """ & Me.cboErrorType & """) AND "
End If
If Not IsNull(Me.cboResponsibility) Then
strWhere = strWhere & "([Decision] = """ & Me.cboResponsibility & """) AND "
End If
If Not IsNull(Me.txtStartDate) Then
strWhere = strWhere & "([Date of Error] >= " & Format(Me.txtStartDate, conJetDate) & ") AND "
End If
If Not IsNull(Me.txtEndDate) Then
strWhere = strWhere & "([Date of Error] < " & Format(Me.txtEndDate + 1, conJetDate) & ") AND "
End If
lngLen = Len(strWhere) - 5
If lngLen <= 0 Then
MsgBox "No criteria", vbInformation, "Nothing to do."
Else
strWhere = Left$(strWhere, lngLen)
'Debug.Print strWhere
Me.Filter = strWhere
Me.FilterOn = True
End If
End Sub
I am removing the filters with the following code:
Private Sub cmdResetFilter_Click()
Dim ctl As Control
For Each ctl In Me.Section(acHeader).Controls
Select Case ctl.ControlType
Case acTextBox, acComboBox
ctl.value = Null
End Select
Next
Me.FilterOn = False
End Sub
Please can someone suggest a solution?
If further information is required, let me know and I will oblige.
Many thanks.
The date format must be either the "reverse" US format (mm/dd/yyyy) or the ISO format (which also works for ADO). So try:
Const conJetDate = "\#yyyy\/mm\/dd\#"

Run-Time Error '13' Type Mismatch - ACCESS DATABASE

I am trying to compare two text fields txtTrailerNumber and txtSealNumber to the database table Tab_TrailerDetails. [TrailerNumber] and [SealNumber] as listed in the table.
I am trying to get the database to look at the trailer number entered into the form, and if it finds a duplicate value it then looks at the seal number entered into the form. If both values have a duplicate found in the table it should throw up the Msg_Box error code.
Private Sub txtSealNumber_AfterUpdate()
Dim NewTrailer, NewSeal As String
Dim stLinkCriteria As String
'Assign the entered Trailer Number and Seal Number to a variable
NewTrailer = Me.txtTrailerNumber.Value
NewSeal = Me.txtSealNumber.Value
stLinkCriteria = ("[TrailerNumber]='" & NewTrailer & "'" And "[SealNumber]='" & NewSeal & "'")
If Me.txtTrailerNumber = DLookup("[TrailerNumber]", "Tab_TrailerDetails", stLinkCriteria) Then
MsgBox "This trailer, " & NewTrailer & ", has already been entered in database," _
& vbCr & vbCr & "along with seal " & NewSeal & "" _
& vbCr & vbCr & "Please make sure Trailer and Seal are not already entered.", vbInformation, "Duplicate information"
'undo the process and clear all fields
Me.Undo
End If
End Sub
The cause of the error is that you have a logical keyword, notably AND inside a string expression. Change your code to
stLinkCriteria = ("[TrailerNumber]='" & NewTrailer & "' And [SealNumber]='" & NewSeal & "'")

How to make listbox display search results based on input in form?

I got a table called "dbInventory" with "ID, InvName, InvQuantity, InvType" and a entry form matching these columns.
What I'm trying to achieve is to have the listbox start displaying search results based on the input.
(My ID column contains barcodes, not autonumbers)
So for instance, if I scan a barcode for an item I already put in the table some other time, I would like it to appear on the listbox right away.
How would one go about that?
It seems like you are wanting to deal with two different methods of entry - either by scanning a barcode (which would give you the entire barcode) or by the user typing the barcode in.
I would suggest using two controls in tandem - a text box, where the user can either scan a bar code or else type in the start of the barcode (and delete typed in data), and then a list box where matches are displayed.
You can use the text box's Change event to get the .Text property and use that as the basis of the list box's RowSource:
Private Sub txtSearch_Change()
On Error GoTo E_Handle
If Not (IsNull(Me!txtSearch.Text)) Then
Me!lstInventory.RowSource = "SELECT ID, InvName, InvQuantity, InvType FROM dbInventory WHERE ID LIKE '" & Me!txtSearch.Text & "*' ORDER BY ID ASC;"
Else
Me!lstInventory.RowSource = "SELECT ID, InvName, InvQuantity, InvType FROM dbInventory ORDER BY ID ASC;"
End If
sExit:
On Error Resume Next
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "frmInventory!txtSearch_Change", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
End Sub
I'm not sure whether scanning a barcode into the text box will trigger the OnChange event - it should do!!
If you are now using 2 different controls to search (part matching on ID and Name) then you should use a small procedure that creates the RowSource of the ListBox as needed, and then call it from the OnChange event of either text box. Something like the code below should get you started:
Private Sub txtSearchID_Change()
Call sSearchForInventory(Nz(Me!txtSearchID.Text, ""), Nz(Me!txtSearchName.Value, ""))
End Sub
Private Sub txtSearchName_Change()
Call sSearchForInventory(Nz(Me!txtSearchID.Value, ""), Nz(Me!txtSearchName.Text, ""))
End Sub
Sub sSearchForInventory(strID As String, strName As String)
On Error GoTo E_Handle
Dim strSQL As String
If Len(strID) > 0 Then
strSQL = " AND ID LIKE '" & strID & "*' "
End If
If Len(strName) > 0 Then
strSQL = strSQL & " AND InvName LIKE '" & strName & "*' "
End If
If Left(strSQL, 4) = " AND" Then
strSQL = "WHERE " & Mid(strSQL, 6)
End If
Me!lstInventory.RowSource = "SELECT ID, InvName, InvQuantity, InvType FROM dbInventory " & strSQL & " ORDER BY ID ASC;"
Me!lstInventory.Requery
sExit:
On Error Resume Next
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "sSearchForInventory", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
End Sub
Notice that you need to use the .Text property of the control that is being changed, but the .Value property of the other control.
Regards,

How do I allow the addition of a value to a table through a combo box in Microsoft Access?

I'm creating my fist Microsoft Access database. I need combo boxes that allow for selection from a list and also addition of values to the field that the combo box is pulling the selections from.
After a lot of googling, I found this example VBA code.
Private Sub cboMainCategory_NotInList(NewData As String, Response As Integer)
On Error GoTo Error_Handler
Dim intAnswer As Integer
intAnswer = MsgBox("""" & NewData & """ is not an approved category. " & vbcrlf _
& "Do you want to add it now?" _ vbYesNo + vbQuestion, "Invalid Category")
Select Case intAnswer
Case vbYes
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO tlkpCategoryNotInList (Category) "
& _ "Select """ & NewData & """;"
DoCmd.SetWarnings True
Response = acDataErrAdded
Case vbNo
MsgBox "Please select an item from the list.", _
vbExclamation + vbOKOnly, "Invalid Entry"
Response = acDataErrContinue
End Select
Exit_Procedure:
DoCmd.SetWarnings True
Exit Sub
Error_Handler:
MsgBox Err.Number & ", " & Error Description
Resume Exit_Procedure
Resume
End Sub
If I use the unaltered example, it doesn't throw an error, but doesn't let me enter a new value.
I tried to alter the code to fit my database but this block throws a syntax error (I've tried to troubleshoot, but I'm new to VBA, and can't find an appropriate linter).
Option Compare Database
Private Sub Combo26_NotInList(NewData As String, Response As Integer)
On Error GoTo Error_Handler
Dim intAnswer As Integer
intAnswer = MsgBox("""" & NewData & """ is not in the database yet " & vbcrlf _
& "Do you want to add it now?" _ vbYesNo + vbQuestion, "new chemical")
Select Case intAnswer
Case vbYes
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO chemical_IDNotInList (chemical) "
& _ "Select """ & NewData & """;"
DoCmd.SetWarnings True
Response = acDataErrAdded
Case vbNo
MsgBox "Please select an item from the list.", _
vbExclamation + vbOKOnly, "Invalid Entry"
Response = acDataErrContinue
End Select
Exit_Procedure:
DoCmd.SetWarnings True
Exit Sub
Error_Handler:
MsgBox Err.Number & ", " & Error Description
Resume Exit_Procedure
Resume
End Sub
I need a functioning combo box that both lets me select from existing values and add new ones.
MsgBox syntax is missing a comma to separate arguments.
intAnswer = MsgBox("""" & NewData & """ is not an approved category. " & vbcrlf _
& "Do you want to add it now?", vbYesNo + vbQuestion, "Invalid Category")
Line continuation is started by a blank in front of an underscore, at the end of the line, not at the beginning.
DoCmd.RunSQL "INSERT INTO tlkpCategoryNotInList (Category) " _
& "Select """ & NewData & """;"
or
DoCmd.RunSQL "INSERT INTO tlkpCategoryNotInList (Category) " & _
"Select """ & NewData & """;"
Your SQL insert command dont' look right.
Try this:
You can set the limit to yes = to yes.
The, for the no in list event, you can use the following code:
Private Sub Combo33_NotInList(NewData As String, Response As Integer)
Dim strSql As String
If MsgBox(NewData & " not in list, add?", _
vbYesNo + vbQuestion) = vbYes Then
strSql = "insert into tblStudents (name) values(" & NewData & ")"
CurrentDb.Execute strSql
Response = acDataErrAdded
End If
End Sub
The insert format is as above - there is no select command.
Note I used a table name of Students, and field name of Sname. So, just
change the table name, and the field to whatever you used.

Search Query Works First Time but subsequent runs get run-time error 3075 extra ) in query expression

I have gone through all previous questions asked and even tried the solutions but to no avail so here's my dilemna. I have used a search query from Allenbrowne which was initially great. However, I wanted to add to the search criteria which again I have done and when searching for the first time I got the results I was looking for. I now use a different code to remove all the search criteria and to unfilter the form (split form). Again everything works. Now I want to search again either using the same of different parameters and this time I get the run-time error 3075 stating that I have an extra ) in the query expression. I have even looked up the query to see where this extra ) is but to no avail. The code is as follows and it errors on Me.Filter = strWhere. I have also provided the reset filter when clearing the search screen and wanting to start a new search. Any help would really be appreciated.
Option Compare Database
Option Explicit
Private Sub cmdFilter_Click()
Dim strWhere As String 'The criteria string.
Dim lngLen As Long 'Length of the criteria string to append to.
'***********************************************************************
'Look at each search box, and build up the criteria string from the non-blank ones.
'***********************************************************************
If Not IsNull(Me.txtCustID) Then
strWhere = strWhere & "([Customer_ID] = " & Me.txtCustID & ") AND "
End If
If Not IsNull(Me.txtJobID) Then
strWhere = strWhere & "([Job_ID] = " & Me.txtJobID & ") AND "
End If
If Not IsNull(Me.txtName) Then
strWhere = strWhere & "([Name] Like ""*" & Me.txtName & "*"") AND "
End If
If Not IsNull(Me.TxtPostcode) Then
strWhere = strWhere & "([Postcode] = ""*" & Me.TxtPostcode & "*"") AND "
End If
If Not IsNull(Me.txtCompany) Then
strWhere = strWhere & "([CompanyName] Like ""*" & Me.txtCompany & "*"") AND "
End If
If Not IsNull(Me.txtLocation) Then
strWhere = strWhere & "([Location] Like ""*" & Me.txtLocation & "*"") AND "
End If
If Not IsNull(Me.CboStatus) Then
strWhere = strWhere & "([Status] = " & Me.CboStatus & ") AND "
End If
If Not IsNull(Me.CboSource) Then
strWhere = strWhere & "([EnquirySource] = " & Me.CboSource & ") AND "
End If
'See if the string has more than 4 characters (a trailng " AND ") to remove.
lngLen = Len(strWhere) - 4
If lngLen <= 0 Then 'Nah: there was nothing in the string.
MsgBox "No criteria", vbInformation, "Nothing to do."
Else 'Yep: there is something there, so remove the " AND " at the end.
strWhere = Left$(strWhere, lngLen)
'For debugging, remove the leading quote on the next line. Prints to Immediate Window (Ctrl+G).
Debug.Print strWhere
'Finally, apply the string as the form's Filter.
Me.Filter = strWhere
Me.FilterOn = True
End If
End Sub
Private Sub cmdReset_Click()
'Purpose: Clear all the search boxes in the Form Header, and show all records again.
Dim ctl As Control
'Clear all the controls in the Form Header section.
For Each ctl In Me.Section(acHeader).Controls
Select Case ctl.ControlType
Case acTextBox, acComboBox
ctl.Value = ""
Case acCheckBox
ctl.Value = False
End Select
Next
'Remove the form's filter.
Me.FilterOn = False
End Sub
See this ctl.Value = "" in cmdReset_Click()? I would guess that when you clear the controls, one of them is ending up a zero-length string, but your test in building the filter is for null, not zero-length strings, so something, most likely one of the numerics, is ending up somefield=<blank>. Try:
ctl.Value = Null
As an aside, there is no point in using equals with a wild card:
strWhere = strWhere & "([Postcode] = ""*" & Me.TxtPostcode & "*"") AND "
Should be:
strWhere = strWhere & "([Postcode] Like ""*" & Me.TxtPostcode & "*"") AND "
Or
strWhere = strWhere & "([Postcode] = """ & Me.TxtPostcode & """) AND "