Access date comparison does not work for specific dates - ms-access

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).

Related

Multiple filters on a subform

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,

DoCmd.SearchForRecord with multiple criteria in Access 2013

I have a form pulling data off an SQL Server table. The form has two unbound comboboxes. Users first select from comboName, then comboDate, then the form will retrieve the record associated with the values.
'comboDate AfterUpdate VBA macro
DoCmd.SearchForRecord , "", acFirst, "[Name] = " & "'" & comboName.Value & "'" & _
" and [Date] = " & "'" & Format(comboDate, "yyyy-mm-dd") & "'"
If I use Name = comboName.Value alone it will retrieve the first record for that name, but if I add the Date criteria, or use the Date criteria without Name, the combobox will no longer retrieve the record. It just stays on the current one. I have already converted the Access date format to match the SQL Server. What else needs to be done?
Access needs # symbols for it to recognize it as a date. It works when I change the query to this.
'comboDate AfterUpdate VBA macro
DoCmd.SearchForRecord , "", acFirst, "[Name] = " & "'" & comboName.Value & "'" & _
" and [Date] = " & "#" & Format(comboDate, "yyyy-mm-dd") & "#"

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.

Order of records that DLookup uses to return first value (Access VBA)

long time stalker but first time poster here so apologies for any social faux pas I make.
I am trying to use DLookup to search for a record in a table using VBA. The specific record I am after is the one closest in date to sdate (a user specified date) which also meets some other criteria. There are likely to be a couple of records with dates prior to sdate which meet the same criteria, and I am only interested in the one which is chronologically closest to sdate.
The following is a simplified example of the code I am using to try and achieve this. I use baseTestString as there are quite a few similar DLookup expressions so it saves typing and clarifies the code slightly (to me at least).
DoCmd.OpenTable ("Results")
DoCmd.SetOrderBy "[Survey_Date] Desc"
DoCmd.Close acTable, ("Results")
'set a new criteria for baseline testing using Dlookup
basetestString = "[Equipment_ID] = '" & equipID & "' AND [Baseline?] = True _
AND format([Survey_Date],""ddmmyyyy"") < format(" _
& sdate & ",""ddmmyyyy"")"
'set variables
[Forms]![results]![text_A] = Nz(DLookup("[Input]", "[results]", _
basetestString))
I believed (perhaps naively) that DLookup returns the first record it finds that matches the criteria specified. So, my code was designed to sort the table into chronological order, thinking that this would be the order that DLookup would cycle through the records.
However, each time I run the code, I am returned the lowest possibly date that matches the criteria rather than the one closest to sdate. After some playing around, I believe that DLookup uses the primary key as its basis for cycling through the records (the earlier dates are entered earlier, and hence given a primary key using autonumber which is lower than later dates).
This leads to me my questions...
1) I am correct in believing this is what is happening when I am returned the wrong record?
2) Is there a way to use DLookup in the way I am attempting? Can I choose which field is used to order the records for DLookup? Assigning the date field as the primary key is not possible as the dates might not always be unique.
3) Is there any other way I can achieve what I am trying to do here?
Thank you very much
It is always unsafe to rely on an order of records in a relational database. You could use DMax to get the date you need, but I think that in this case a recordset would be quicker.
Dim rs As DAO.Recordset
Dim db As Database
Dim ssql As String
Set db = CurrentDB
ssql=" SELECT input" _
& " FROM results" _
& " WHERE results.[baseline?] = true" _
& " AND results.equipment_id = '" & equipID & "'" _
& " AND results.survey_date = (SELECT" _
& " Max(results.survey_date) " _
& " FROM results" _
& " WHERE results.[baseline?] = true" _
& " AND results.equipment_id = '" & equipID & "'" _
& " AND results.survey_date <#" & Format(sdate,"yyyy/mm/dd") & "#)"
Set rs = db.OpenRecordset(ssql)
strInput = rs("Input")
Debug.Print strInput
You can also check the number of records returned, in case of an error.

Why won't access return the correct values within the date range?

The query it not handling the date ranges correctly.
I have a table with values stored like "01/10/2013 11:00:00 PM" for DateStamp. Ranging from 25/09/2013 1:00:00 AM to 02/10/2013.
The textboxs values are dtBegin = "28/09/2013" and dtEnd = 01/10/2013.
dSumUsuage = DSum("Average", "tblScadaHourly", "[DateStamp] >= #" & dtBegin & "#" & " AND " & "[DateStamp] < #" & dtEnd & "#" & " AND ([Station] ='" & sStationName & "')")
This query is returning an error of "Invalid use of Null". But their is data between these dates and for that station name.
This may be a classical Access date formatting error: When using the english date format with slashes, Access thinks that you use the format MM/DD/YYYY, unless this results in an invalid date (then it tries DD/MM/YYYY).
Therefore, I prefer using the international date format YYYY-MM-DD.
In your case, this might result in a query for ">=2013-09-28 And <2013-01-10", which obviously can't return any results. >> with the international format, it would ask for ">=2013-09-28 And <2013-10-01"
As the previous answer, your where string is malformed, as Your dSumUsuage is of type Date, it does not accept Null, as no records meet your bad WHERE constraints, so an error is raised.
We use this procedure:
Public Function FormatDateTimeVb(ByVal varDateTime)
FormatDateTimeVb = "#" & Format(varDateTime, "yyyy-mm-dd hh:mm:ss") & "#"
End Function
Using this function to form date time string, now we get the sum of tblScadaHourly.Average:
dSumUsuage = DSum("Average", "tblScadaHourly", _
"[DateStamp] >= " & FormatDateTimeVb(dtBegin) _
& " AND [DateStamp] < " & FormatDateTimeVb(dtEnd) _
& " AND ([Station] = '" & sStationName & "')")