Finding the next occurrence of a given date with MS Access query - sql

I'm currently working on a database that stores software licensing information such as software name, purchase date, cost, quantity, etc... After the software has been owned for 12 months, we must pay a maintenance fee.
My question therefore, is how to design a query that will take the purchase date and compute the next occurrence of that date to be stored in the maintenance date field. Ex) If a license was purchased on 12/31/1999, I would need to pay maintenance on 12/31/2016.
I don't have a lot of experience with MS Access or SQL queries, and after researching this for a while, I am not even sure this is possible. I would appreciate any help you guys could give me!

Here's a function that will do exactly this:
Public Function DateNextAnnualDay( _
ByVal AnnualDay As Date) _
As Date
Dim SomeDate As Date
Dim NextAnnualDay As Date
Dim Years As Integer
SomeDate = Date
NextAnnualDay = AnnualDay
Years = DateDiff("yyyy", AnnualDay, SomeDate)
If Years < 0 Then
' Don't calculate hypothetical annual days.
Else
NextAnnualDay = DateAdd("yyyy", Years, AnnualDay)
If DateDiff("d", SomeDate, NextAnnualDay) <= 0 Then
' Next annual day falls earlier in the year than SomeDate.
NextAnnualDay = DateAdd("yyyy", Years + 1, AnnualDay)
End If
End If
DateNextAnnualDay = NextAnnualDay
End Function

Here is the syntax
SELECT DateAdd("yyyy",1,[MyDate]) AS MaintDate
FROM Table;

If you need to do more complicated querying you can write a function in a module and then access it in a query using VBA. For instance you can iterate through a loop to match a condition
Function GetNextDate(ByVal dteOriginalDate As Date) As Date
While dteOriginalDate <= DateTime.Now
dteOriginalDate = DateAdd("Yyyy", 1, dteOriginalDate)
Wend
GetNextDate = dteOriginalDate
End Function
Will iterate adding one year from the original date to the point at which the date is in the future. You can the build it into a query (using right-click -> build) so that each row runs through your code and applied the logic.
This will allow you to store the original licence date in your database and calculate the next due date without having to know (or amend) the intervening years.

Related

VBA - Selecting cells that contain dates for the past 5 years

I currently have a spreadsheet that has the dates (excluding weekends and holidays) for the past 10 years in column A. For example, A1 contains "7/19/2007" and A2520 contains "7/19/2017"
Column E contains the closing price for the stock SPY on those corresponding dates.
I am trying to figure out the standard deviation for the past 5 years. In order to do so, my idea was to write a VBA code that would select today's date and the previous five years, and then use that to calculate the standard deviation.
This list is updated everyday, meaning tomorrow, it will contain 7/20/2017 and the closing price for that day. My issue is that I cannot figure out how to make it so it will select today's date and the past five years, so then I can calculate the standard deviation.
Thank you guys for all your help! Sorry if this seems simple, I have just started learning VBA last week!
How's this? I make a few assumptions, like your dates are contiguous, and there's no empty cell in your Date column. I also assume your dates are in order, ascending. (So your day 10 years ago is in say row 10, and today is in row 1000).
Sub get_difference()
Dim dateRng As Range, cel As Range, priceRng As Range
Dim dateCol As Long, stockCol As Long, lastDate As Range
Dim tdyDate As Date, decadeAgo As Date
dateCol = 1 ' column A has your dates
stockCol = 5
tdyDate = WorksheetFunction.Text(Now(), "mm/dd/yyyy")
decadeAgo = get_Previous_Date(tdyDate)
Debug.Print decadeAgo
With Sheets("Stock Prices") ' change name as necessary
With .Columns(dateCol)
Set lastDate = .Find(what:=tdyDate) ' Assuming no break in data from A1
'lastDate.Select
Set cel = .Find(what:=decadeAgo)
'cel.Select
End With
Set rng = .Range(.Cells(cel.Row, dateCol), .Cells(lastDate.Row, dateCol))
'rng.Select
Set priceRng = rng.Offset(0, stockCol - dateCol)
'priceRng.Select
'priceRng.Offset(0, 1).Select
priceRng.Offset(0, 1).FormulaR1C1 = "=IFERROR((RC[-1]/R[-1]C[-1])-1,"""")"
End With
End Sub
Function get_Previous_Date(Dt As Date) As Date
' https://www.mrexcel.com/forum/excel-questions/37667-how-subtract-year-date-2.html
Dim numYearsBefore as Long, numDaysBefore as Long, numMonthsBefore as Long
numYearsBefore = 10 ' Change this to any amount of years
numDaysBefore = 0
numMonthsBefore = 0
get_Previous_Date = DateSerial(Year(Dt) - numYearsBefore, Month(Dt) - numMonthsBefore, Day(Dt) - numDaysBefore)
End Function
Make changes as needed, i.e. sheet name (I called mine "Stock Prices"), and the columns. It's also a little verbose, and could be made more compact, but I figured it'd help you learn to keep it like that. I suggest stepping through with F8 to see what happens, and uncommenting the .select lines so you can visually see what it's doing.

How to determine week number within calendar quarter period VB6

Having some trouble locating a function to determine the week number of a quarter period in a standard date based (i.e. Day 1 = 2017-01-01) calendar table.
My table has the following information stored :
Quarter Number, Beginning Date, End Date, Number of Days;
As an example, for the first quarter of calendar year, the result for Week 1 would be 1, Week 14 would be 1, going through each quarter until the final week of quarter 4.
Any ideas please help?
I don't believe there is a built-in function for this. If I understand what you're asking, this is a trivial function to write. You don't include any code so I'm just giving you the most basic example. You want to do something similar to this.
Public Function GetWeekInQuarter(ByVal WeekNumber As Integer) As Integer
Const intWeeksInQuarter = 13
Dim intResult As Integer
intResult = WeekNumber Mod intWeeksInQuarter
'if intResult <> intWeeksInQuarter = 0 then this is the 13th week
GetWeekInQuarter = IIf(intResult <> intWeeksInQuarter, intResult, intWeeksInQuarter)
End Function

SQL language in MS ACCESS 2016

i need help with some query in MS ACCESS 2016 with SQL language.
I have a table with 20 employers, and the table includes name, last name, gender, date of birth, date of employment and payment.
I need to calculate specific age, I mean, I want to know who is for example 25 years old of my employers, i dont know how to write command in SQL language to calculate that, i would be very grateful if someone can help me.
You cannot calculate 100% correct age directly in SQL in a simple way.
So use an UDF (user defined function) like this:
Public Function AgeSimple( _
ByVal datDateOfBirth As Date) _
As Integer
' Returns the difference in full years from datDateOfBirth to current date.
'
' Calculates correctly for:
' leap years
' dates of 29. February
' date/time values with embedded time values
'
' DateAdd() is used for check for month end of February as it correctly
' returns Feb. 28. when adding a count of years to dates of Feb. 29.
' when the resulting year is a common year.
' After an idea of Markus G. Fischer.
'
' 2007-06-26. Cactus Data ApS, CPH.
Dim datToday As Date
Dim intAge As Integer
Dim intYears As Integer
datToday = Date
' Find difference in calendar years.
intYears = DateDiff("yyyy", datDateOfBirth, datToday)
If intYears > 0 Then
' Decrease by 1 if current date is earlier than birthday of current year
' using DateDiff to ignore a time portion of datDateOfBirth.
intAge = intYears - Abs(DateDiff("d", datToday, DateAdd("yyyy", intYears, datDateOfBirth)) > 0)
End If
AgeSimple = intAge
End Function
Copy and paste the code into an empty module.
Then run a query:
Select *, AgeSimple([DateOfBirth]) As Age
From YourTable
Where AgeSimple([DateOfBirth]) >= 25
Of course, replace table and field names with those of yours.

Out of a set of data returned grouped by months, only the initial month is returning incorrect data

I am trying to return data for the last 24 months as of the end of last month. Only the initial month returns incorrect data, while all the other months are correct. I believe the issue is in the strBeginDate = section of the code. Any ideas what would be causing partially returned data for the initial month? Thank you very much.
Sub GetStaticApprovalRates_Slide6()
Dim strBeginDate
Dim strEndDate
strEndDate = Sheets("Instructions").Range("EndDate").Value
strBeginDate = DateAdd("m", -23, strEndDate) + 1
Sheets("Slide6Data").Select
It's hard to say exactly what's wrong based only on what you posted. But I do see that you are calculating the start date based on the end date, by only subtracting months. There is no allowance for days. So you might be missing some of that first month by not allowing for the early days of that first month.
That is , if end date occurs mid-month, I think your algorithm would cause start date to be mid-month also. Perhaps missing days 1-x of that first month.

In VB, calculating the 5th working day of every month

In VB, what coding could I use to calculate the 5th working day of every month? And if the 5th day is a holiday to go up one day.
You would need a list of holiday dates with which to compare. You would need to build and store that list separately. You did not say what variant of VB (VBA? VB.NET?) but in VB.NET you could do:
Dim datevalue As DateTime = New DateTime(DateTime.Year, DateTime.Month, 1)
Dim dayIsFound As Boolean = False
Dim workDays As Integer
workDays = 1
While Not dayIsFound
If ( dateValue.DayOfWeek <> DayOfWeek.Saturday _
And dateValue.DayOfWeek <> DayOfWeek.Sunday _
And Not HolidayList.Contains( dateValue ) _
workDays = workDays + 1
End If
If index >= 5 Then
dayIsFound = True
Else
dateValue = dateValue.AddDays(1)
End If
End While
Technically, it is possible to build an algorithm that determines the major holidays based on Federal guidelines (in the US) but it is complicated and may not conform to the holidays of the company to whom you are building this component.
The problem has 2 main components - first you need a list of public holidays, and second you need to count days of the week which are working days in your locale.
You can hard code your holidays for a quick solution, and if you want this code to keep working without modification you will need to Google for some algorithms / functions to calculate your holidays. Here is a link to some sample calculation functions for holidays, including Easter. http://www.cpearson.com/EXCEL/holidays.htm
Your main function can use the VB functions Weekday and WeekdayName (if needed) in conjunction with your list of public holidays to count all days that fall on a normal working day which isn't in your list of public holidays.
Use Weekday function for Saturday and Sunday. Holidays are dependent on the location and country and you need to implement your own function for that.
You need to count each valid working day until you get to the fifth one. E.g.
index = 0
Do
If dateValue.DayOfWeek <> DayOfWeek.Saturday _
AndAlso dateValue.DayOfWeek <> DayOfWeek.Sunday _
AndAlso Not HolidayList.Contains( dateValue ) Then
index = index + 1
If index >= 5 Then _
Exit Do
End If
dateValue = dateValue.AddDays(1)
Loop