Multiple filters on a subform - ms-access

Trying to apply 2 filters at the same time to a subform.
Want to see records between DATES X and Y, and from BRANCH Z only.
Working fine alone, but can't use both at the same time. I know it's something
Current code:
Private Sub Command39_Click()
If IsNull(Me.txtFrom) Or IsNull(Me.txtTo) Then
MsgBox "Insert date!"
Else
With Me.frmDailyRevenue.Form
.Filter = "[DateDbl] BETWEEN " & Me.txtFromDbl & " AND " & Me.txtToDbl & "" And [F5] = " & Me.cboBranch & """
.FilterOn = True
End With
End If
End Sub
This is basically bits of code I got from the web as I'm really new to this.
So, all advice is welcome.

Try this:
.Filter = "[DateDbl] BETWEEN #" & Format(Me.txtFromDbl,"mm\/dd\/yyyy") & _
"# AND #" & Format(Me.txtToDbl,"mm\/dd\/yyyy") & "# And [F5] = '" & Me.cboBranch & "'"
I supposed that Me.cboBranch is text. If this field contains code, remove single quotes.
Also I noticed that controls you check and controls you take data from are different (Me.txtFrom and Me.txtFromDbl, Me.txtTo and Me.txtToDbl), check this.

Found the problem.
Using BETWEEN and AND for the date range was causing some conflict with the second AND to add the filter for field F5.
So I switched to use >= and <= as follows:
.Filter = "[DateDbl] >= " & Me.txtFromDbl & " AND [DateDbl] <= " & Me.txtToDbl & " AND [F5] = " & Me.cboBranch & ""
Just to clarify, for people that might come for this later, you should use # as Sergey pointed out if you have a date field, my date is in double format, so I don`t need to.
Thanks,

Related

Multiple filter clauses for query and subsequent report from unbound form controls, button activated

Been a while since I used Access and now stuck with a reporting problem.
I have a form, with various unbound controls. There a start date, end date and three levels of business/asset/location in combo boxes.
I can get my query and report to work for each of these as individual 'where' clauses when clicking on a button. That's fine.
However I would like to know what code I need to use when clicking a button so I can combine one or more of the above controls to filter the report i.e. my date range + Business, or date + Business + Asset etc.
I have been trawling the internet and testing different variations but seem to have gone through the error book so far.
My latest effort (on click) as one long string gives me a data mismatch error. If I remove the BU/Asset/Facility parts then my date range code does work. However, it's the combination of these I want to filter by.
DoCmd.OpenReport ReportName:="rptVerification_Results", View:=acViewPreview, WhereCondition:="[Date Entered] Between #" & Me.StartDate & "# AND #" Me.EndDate & "#""" And "BU = " & Me.cboBusiness & "" And "Asset = " & Me.cboAsset & "" And "Facility = " & Me.cboFacility & ""
As you can probably tell I'm winging it and need some direction please.
Thanks
It can be tricky to get the combination of quoted strings and form fields right, as you need to be aware of which quotes are being used to concatenate the WhereCondition string together and which quotes are being presented to the query engine. You also need to know which fields are text and which are numeric, because text fields need to be enclosed in quotes in the resulting string, while numerics don't. I'm assuming below that cboBusiness, cboAsset and cboFacility are all text.
I suggest you create a separate variable to store your WhereCondition in:
Dim myWhereCondition As String
myWhereCondition = "[Date Entered] BETWEEN #" & Me.StartDate & "# AND #" & Me.EndDate
& "# AND BU = '" & Me.cboBusiness
& "' AND Asset = '" & Me.cboAsset
& "' AND Facility = '" & Me.cboFacility & "'"
DoCmd.OpenReport ...
WhereCondition:=myWhereCondition
You can then create a debug breakpoint on the "DoCmd" statement and check the value of "myWhereCondition" in the Immediate window, to make sure it is formed correctly, before DoCmd runs.
IIRC, you can use apostrophes/single quotes as an alternative to double quotes in MS Access, as I've done above. If this is not the case, then each of the single quotes above would need to be converted to "double double quotes" (because a double quote on its own would terminate the string).
The somewhat messier "double quotes everywhere" version of the WhereCondition would be:
myWhereCondition = "[Date Entered] BETWEEN #" & Me.StartDate & "# AND #" & Me.EndDate
& "# AND BU = """ & Me.cboBusiness
& """ AND Asset = """ & Me.cboAsset
& """ AND Facility = """ & Me.cboFacility & """"
Note that if any of the cbo fields are numeric, you need to remove the corresponding single (or double double) quotes from each side of that field.
Try this WhereCondition:
Dim WhereCondition As String
' First, adjust the WhereCondition:
WhereCondition = "([Date Entered] Between #" & Format(Me!StartDate.Value, "yyyy\/mm\/dd") & "# And #" & Format(Me!EndDate.Value, "yyyy\/mm\/dd") & "#) And BU = '" & Me.cboBusiness & "' And Asset = " & Me.cboAsset & " And Facility = " & Me.cboFacility & ""
' Then, open report:
DoCmd.OpenReport ReportName:="rptVerification_Results", View:=acViewPreview, WhereCondition:=WhereCondition

Access date comparison does not work for specific dates

I made a form to update historical data and a subform that is used to check the result! Everything works fine except one small problem.
The result of my date comparison is not correct for any date that is the first date of any month in 2018!!! (it is driving me craziee)
So my code is below:
Private Sub runbtn_Click()
Me.Refresh
Dim theminimum As String
Dim theprodscID As String
Dim thepurchasedate As Date
If IsNull(Me.purchasedate) = False Then
theprodscID = Str(Me.prodscID)
thepurchasedate = Me.purchasedate.Value
'minimum textbox
theminimum = "Select Top 1 [update value]" & _
" From [product and shareclass level data update]" & _
" Where [product and shareclass level data update].[dataID] =" & Str(1) & _
" And [product and shareclass level data update].[prodscID] =" & theprodscID & _
" And ([product and shareclass level data update].[timestamp] <= #" & thepurchasedate & "#)" & _
" Order by [product and shareclass level data update].[timestamp] DESC"
If CurrentDb.OpenRecordset(theminimum).RecordCount = 0 Then
Me.minimum = Null
Else
Me.minimum = CurrentDb.OpenRecordset(theminimum).Fields(0).Value
End If
So for example, if I have records update value: "hello" on 01/05/2018; "bye" on 01/08/2017. Then, when I enter the purchase date as 01/05/2018, it should give me "hello" but not "bye"! However, if I enter 12/05/2018, it gives me "hello", which is correct! I find that this error occurs for some dates that I put as timestamp, but works for other dates!
I checked my code and I think it is correct. I don't know what the problem is!
Thanks,
Phylly
Your problem is, that the date value must be properly formatted as a text expression. thus:
" And ([product and shareclass level data update].[timestamp] <= #" & Format(thepurchasedate, "yyyy\/mm\/dd") & "#)" & _
Alternatively, implement my function CSql, or - even better - start using parameters (bing/google for that).

Multi Criteria Dsum

Im starting to pull my hair out.
I am looking to do a multi criteria dsum that looks at the current user and todays date.
Tried many variations but must be missing something very simple so any help is appreciated
StatusBox = DSum("[Task_time]", "[tbl_Data]", "[CDP] = '" & Environ("username") & "' and [Record_Date] = '" & Date & "'")
Dates must be enclosed with #. Also they need to be formatted in order to return the desired result.
Try this:
StatusBox = DSum("[Task_time]", "[tbl_Data]", "[CDP] = '" & Environ("username") & "' and [Record_Date] = #" & Format(Date, "mm/dd/yyyy") & "#")
You are just making it slightly too complicated:
StatusBox = DSum("[Task_time]", "[tbl_Data]", "[CDP] = '" & Environ("username") & "' And [Record_Date] = Date()")

UPDATE SET WHERE Partially working on listbox - Microsoft Access VBA

I'm totally stumped at this one.. Skip to bottom to read problem
Here's my listbox (DocumentList) that takes the fields from the 'Documents' Table:
Document Name Status Notes Consultation Notes
Doc A Started Document Started Aim to process on 05/05/16
Doc B Processing Document Processing Aim to complete on 05/05/16
Doc C Complete Complete on 01/01/16 N/A
I have the onclick event set so that when you select a row from the listbox, it assigns each field to a text box/Combobox.
textboxes/Combobox names:
txtDocument
StatusCombo
txtNotes
txtConNotes
code for each one in 'DocumentList' click event:
Private Sub DocumentList_Click()
txtDocument = DocumentList.Column(0)
StatusCombo = DocumentList.Column(1)
txtNotes = DocumentList.Column(2)
txtConNotes = DocumentList.Column(3)
After the data is assigned to them from the listbox, you can edit it. I have an update button, which when pressed will replace everything in the database with everything in the textboxes/Combobox. The listbox is then re-queried and displays the updated data.
Heres the code for my update button:
Private Sub UpdateButton_Click()
CurrentDb.Execute "UPDATE [Documents] " & _
"SET [Document Name] = '" & Me.txtDocument & "'" & _
", [Status] = '" & StatusCombo.Value & "'" & _
", [Notes] = '" & Me.txtNotes & "'" & _
", [Consultation Notes] = '" & Me.txtConNotes & "'" & _
"WHERE [Document Name] = '" & DocumentList.Column(0) & "'" & _
"AND [Status] = '" & DocumentList.Column(1) & "'" & _
"AND [Notes] = '" & DocumentList.Column(2) & "'" & _
"AND [Consultation Notes] = '" & DocumentList.Column(3) & "'"
DocumentList.Requery
End Sub
My problem is the code only works on 2 out of 3 of the documents. All aspects of the code work, but only on some of the documents. This doesn't make any sense to me. At first I thought it may be a spelling error, but even if it was, none of the documents should get updated.. But some of them do, 1 doesn't..
Any ideas why this code updates some documents, but doesn't update others?
Nothing is updated when [Documents].[Consultation Notes] is Null, because the WHERE clause targets an empty string instead ... "'" & DocumentList.Column(3) & "'" ... so no matching row is found.
The task would be simpler if you add an autonumber primary key, ID, to the [Documents] table. Then include ID in the list box Row Source, and use that value in the WHERE clause to target the row you want to update. (The ID column doesn't have to be visible in the list box; you can set its column width property to zero.)
Then your WHERE clause can be much simpler: just target the record whose ID matches the ID column value of the selected list box row. That strategy would also avoid the complication of "Null is never equal to anything, not even another Null".
Finally, consider a parameter query for the UPDATE instead of concatenating values into a string variable.

DCount will nor return 0 but returns Error instead

Test = DCount("*", "tblWorkNew", "GP = " & GPID & " And Month = #" & Month & "#")
This function gives correct results when the answer is >0. Whenever it's 0, I get #Error. I have tried putting my code within a Nz but that doesn't help either.
I tried to duplicate on a Northwind db what I believe you are trying to do. I used the Order List form. In the header of that form I created a textbox named txtMonth. The Control Source for txtMonth is =Month([Order Date]). Then I created another textbox in the header named txtMonthOrders with Control Source as =GetMonthSum(). Then I created a function in Modules called GetMonthSum(). This is the function: GetMonthSum = DCount("[Order ID]", "Order Summary", "Month([Order Date]) = '" & Forms![Order List]!txtMonth & "'") . This seems to work.