I need to count the number of shifts worked by people over the last twelve months. I want to use DateSerial. My code works if I input an actual date, not DateSerial. I tested my code by changing DateSerial to return a date other than twelve months ago but my code always gives the figure for the sum of all data - going back more than twelve months. So it ignores MyDt. Where am I going wrong?
Public Function Shifts() As Integer
Dim MyDt As Date
MyDt = DateSerial(Year(Date), Month(Date) - 12, 1) - 1
Shifts = DSum("Shifts", "tblWorkNew", "GP = " & GPLookup & "And Month > #31/10/2012#") 'This works for any date.
Shifts = DSum("Shifts", "tblWorkNew", "GP = " & GPLookup & "And Month > " & MyDt) 'This only gives all data, i.e. ignores MyDt
End Function
MyDt is Date/Time, but you include it as a string in your DSum criteria argument. So transform the value to a string which the db engine recognizes as the date you intend.
Shifts = DSum("Shifts", "tblWorkNew", _
"GP = " & GPLookup & _
" And [Month] > " & Format(MyDt, "\#yyyy-mm-dd\#"))
I added a space before And because it looked like there was one missing. I assumed Month is the name of a field in your tblWorkNew table, so enclosed it in square brackets to inform the db engine you don't want the Month() function instead.
Related
I have 3 record:
day_birth of type Number (1-31);
month_birth of type Short Text ("January");
year_birth of type Number.
How to get in calculated field, full birthday day name from this day?
I tried this one expression:
WeekdayName(Weekday(DateSerial(2003;1;1);2))
But it doesn't work. I get #Type! in my record field.
Well, you can use this:
? format(dateserial(2003,1,1),"ddd")
Wed
or even this:
? format(dateserial(2003,1,1),"dddd")
Wednesday
However, you suggest/state/hint/imply/note that your input month is a LONG TEXT month of January. (short would be Jan).
So, we need to take into account that fact.
(but, why oh why oh why oh why oh why was the DOB not just stored as a simple single datetime column? With such a column, then you are 100% free to break it apart into 3 columns for reporting etc., but always have one simple date column
However, you have what you have, probably not your fault.
So, then:
Dim strTestMonth As String
Dim intTestYear As Integer
Dim intTestDay As Integer
strTestMonth = "January"
intTestYear = 2003
intTestDay = 1
Dim strTestDate As String
Dim strDateFormat As String
strDateFormat = "mmmm/dd/yyyy"
strTestDate = strTestMonth & "/" & intTestDay & "/" & intTestYear
Dim dtDate As Date
dtDate = Format(strTestDate, strDateFormat)
' get day of week as number
Debug.Print Weekday(dtDate)
' get day of week as text
Debug.Print "Short day of week = " & Format(dtDate, "ddd")
Debug.Print "Long day of week " & Format(dtDate, "dddd")
Output:
4
Short day of week = Wed
Long day of week Wednesday
So, approach:
Convert the string into a internal date, and once done, then you are free to spit out the date in any format you want, including use of weekday function, or even format which can return a short day format (wed), or a longer date format (Wednesday).
It not clear if you need this "display" of the week day on the form, or in a report or whatever. So as always the VERY important issue becomes the when/where/how/what point in time you need this expression.
So, you could for example place this function in a standard code module: (not forms code module)
Public Function GetDayOfWeek(strMonth As String, _
intDay As Integer, _
intYear As Integer) As String
Dim strDateFormat As String
Dim dtDate As Date
strDateFormat = "mmmm/dd/yyyy"
dtDate = Format(strMonth & "/" & intDay & "/" & intYear, strDateFormat)
GetDayOfWeek = Format(dtDate, "dddd")
End Function
So, now when ever and "where" ever you need to display the weekday as "text", then you can do this for even a control on that form:
=(GetDayOfWeek([MonthField],[dayField], [YearField]))
So, place the above code in a standard code module (not forms code module), and then in code, or even as a expression on a control in a form, you can pass the 3 values, and it will return/display the day of week in long text format.
Use DateValue and a simple query:
Select
*,
DateValue(Str([year_birth]) & " " & [month_birth] & Str([day_birth])) As BirthDate,
WeekdayName(Weekday(DateValue(Str([year_birth]) & " " & [month_birth] & Str([day_birth])), 2), 2) As BirthWeekday
From
YourTable
I am trying to create a Variable in my report that returns a String with a Date Range that looks like this: 02-01-2018 - 01-31-2019
I have tried this expression:
=FormatDateTime(DateSerial(Year(Now()), Month(Now()), “1”).AddMonths(-12), DateFormat.ShortDate)
& " - " &
FormatDateTime(DateSerial(Year(Now()), Month(Now()), “1”).AddDays(-1))
and it gives me this: 2/1/2018 - 1/31/2019.
I cannot have /'s in the date range because I am using the Variable as the Page Name of the Tablix that will end up as the Sheet [Tab] name in Excel when I export the report. Excel does not seem to accept /'s in the Sheet Names.
In short, I need to be able to dynamically create a date range of 12 months ending at the last date of the previous month - and it should be a string that looks like 02-01-2018 - 01-31-2019.
How about this:
= Today.AddDays(1-Today.Day).AddYears(-1).ToString("MM-dd-yyyy") & " - " & Today.AddDays(-Today.Day).ToString("MM-dd-yyyy")
You can use the VB.NET .ToString to convert to any format that you want.
=TODAY.AddDays(-1).ToString("MM-dd-yyyy")
So your string would be
=TODAY.AddMonths(-12).ToString("MM-dd-yyyy") & " - " & TODAY.AddDays(-1).ToString("MM-dd-yyyy")
You can specify your own date format to use:
=FormatDateTime(DateSerial(Year(Now()), Month(Now()), “1”).AddMonths(-12), "MM-dd-yyyy")
& " - " &
FormatDateTime(DateSerial(Year(Now()), Month(Now()), “1”).AddDays(-1), "MM-dd-yyyy")
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).
I am working on a code from a previous developer. This code has SystemTime set up.
Is there a way to get today date and minus 30 days in this format?
Code Below:
Public Function GetIsoTimestampTest() As String
Dim st As SYSTEMTIME
'Get the local date and time
GetSystemTime st
'Format the result
GetIsoTimestampTest = _
Format$(st.wYear, "0000") & "-" & _
Format$(st.wMonth, "00") & "-" & _
Format$(st.wDay, "00") & "T" & _
Format$(st.wHour, "00") & ":" & _
Format$(st.wMinute, "00") & ":" & _
Format$(st.wSecond, "00") & "Z"
End Function
Build a native date & time, add -30 days, format as a string:
utcInIsoFormat = Format$(DateAdd("d", -30, _
DateSerial(st.wYear, st.wMonth, st.wDay) _
+ TimeSerial(st.wHour, st.wMinute, st.wSecond)), "yyyy-mm-ddThh:nn:ssZ")
SYSTEMTIME appears to be a custom type defined elsewhere in your code. It's not a standard type available in Access VBA. So to use it effectively, you need to find the definition. Also GetSystemTime is also likely a custom function exclusive to your code. Here's a sample definition of a similar type, although it may not be exactly what's implemented in your system: http://custom-designed-databases.com/wordpress/2011/get-milliseconds-or-seconds-from-system-time-with-vba/
That said, System Time would refer to the Windows system time. You also have a native ability in VBA to get time using the Now() function. (https://msdn.microsoft.com/en-us/library/office/gg278671.aspx) This returns a variable with type Date, which is equivalent to a number where the integer represents days and the decimal represents time of day. An example to get 30 days prior to today would be:
Dim lastMonth as Date
Dim formattedDate as String
lastMonth = Now() - 30
formattedDate = Format(lastMonth, "yyyy-mm-ddThh:nn:ssZ")
DateSerial happily accepts a negative day count. Thus:
Public Function IsoDateMinus30() As Date
Dim st As SYSTEMTIME
Dim Result As Date
' Get the local date and time
GetSystemTime st
Result = DateSerial(st.wYear, st.wMonth, st.wDay - 30)
' To include time:
'
' Result = _
' DateSerial(st.wYear, st.wMonth, st.wDay - 30) + _
' TimeSerial(st.wHour, st.wMinute, st.wSecond)
IsoDateMinus30 = Result
End Function
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 & "')")