Function to compute number of periods between two dates - vba

Suppose the flow of time is subdivided into periods:
Period 1 beginning August and ending January
Period 2 beginning February and ending July
Note, that each period is 6 month.
Question
Now suppose two dates A and B are given.
Could you provide an expression (closed formula), which computes the
number of periods where A is within the first and B is within the last
period?
'Closed formula' :: The creation of a procedure isn't an option her.
Let's have a detailed look
Let...
A be the 2nd of March 2015
B be the 15th of January 2018
Thus...
A is part of period 2 beginning February 2015.
B is part of period 1 beginning August 2017.
Therefore...
the difference in periods between A and B is 6.
Since
Period 2 beginning February 2015
Period 1 beginning August 2015
Period 2 beginning February 2016
Period 1 beginning August 2016
Period 2 beginning February 2017
Period 1 beginning August 2017

Try looking into the VBA function DateDiff https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/datediff-function

As formula (assuming your date in A2 and B2):
=(YEAR(EDATE(A2;-1))*2+INT((MONTH(EDATE(A2;-1))-1)/6)) - (YEAR(EDATE(B2;-1))*2+INT((MONTH(EDATE(B2;-1))-1)/6))
As VBA function:
Function datePeriods(ByVal d1 As Date, ByVal d2 As Date) As Long
d1 = DateAdd("m", -1, d1)
d2 = DateAdd("m", -1, d2)
Dim p1 As Long, p2 As Long
p1 = Year(d1) * 2 + ((Month(d1) - 1) \ 6)
p2 = Year(d2) * 2 + ((Month(d2) - 1) \ 6)
datePeriods = p2 - p1
End Function
The basic idea is to "move" the periods to the first and second half of a year, then calculate a numeric value for the year (year * 2) and the "half year" (integer division by 6) and subtract these two values.

Code to test your function. Insert a module in the VBA editor and enter the following code in it:
Option Explicit
Public Function CountPeriods(startDate As Date, endDate As Date) As Long
Dim diffMonths As Long
Dim diffPeriods As Long
diffMonths = DateDiff("m", startDate, endDate)
diffPeriods = diffMonths \ 6
CountPeriods = diffPeriods
End Function
Now enter your start and end dates and refer to the code above like this in cell B1 (or any cell):

Related

DateDiff not working when finding amount of years between two dates

I've got the following formula
number_of_years = DateDiff("yyyy", Date_days_back, Current_Date)
where
Date_days_back = 17/10/2020
Current_Date = 02/08/2021
for some reason this returns "1" when there aren't 365 days apart between these two dates, is something wrong with my formula or is DateDiff calculating this wrong? I would like to get "0" returned as there aren't enough amount of days between these two dates for a year to have passed between the two dates.
Comment: As Scott Stated, if I'm looking from December 31st 2020 and 1st of January 2021, then this function will count this as a year has passed. is there another function that calculates if a years has passed in between two dates where it doesn't do what DateDiff does and instead counts if 365 have passed in between the two dates?
Try to use YearFrac(). By setting the third argument to 1, the function uses the actual number of days in years (taking into account leap years) in its calculations:
Int(WorksheetFunction.YearFrac("2020-12-31", "2021-12-31", 1))
Comparison:
Sub Example()
start_date = CDate("2020-12-31")
end_date = CDate("2021-01-01")
Debug.Print Int(WorksheetFunction.YearFrac(start_date, end_date, 1))
' prints 0
Debug.Print DateDiff("yyyy", start_date, end_date)
' prints 1
End Sub
This seems to work
function yeardiff(d1 as date, d2 as date) as integer
yeardiff = datediff("yyyy", d1, dateadd("yyyy", -1, dateadd("d", 1, d2)))
end function
Tests
print yeardiff("2020-12-31", "2021-12-30")
0
print yeardiff("2020-12-31", "2021-12-31")
1
Of course it will also give,
print yeardiff("2020-12-31", "2020-12-30")
-1
And if something different is desired then a conditional would be needed.

Populate a column with dates starting from 1 jan to 31 dec given the year

I want to write a code in excel-vba which populates the dates for a particular year in a column on the sheet.
The code should also take into account leap years. Say, I have entered the year in Cell B1 (as 2020), so Column A should be populated with 366 date entries(taking into account the leap year).
You can loop on a Date variable:
Sub dater()
Dim yr As Long, d As Date, i As Long
yr = Range("B1").Value
For d = DateSerial(yr, 1, 1) To DateSerial(yr, 12, 31)
i = i + 1
Cells(i, 1) = d
Next d
End Sub
This will automatically handle leap-years and populate either 366 or 365 cells as appropriate. (format column A to suit your needs)

VB.net work out number of days between two dates [duplicate]

This question already has answers here:
How to find the number of days between two dates / DateTimePickers
(3 answers)
Closed 6 years ago.
I am trying to work out the number of days between two dates and whether it is a full month or not.
I currently have this code:
Dim fromdate As Date
Dim todate As Date
Dim timespan
Dim num_days As String
Dim month As DateTime
fromdate = Date.Parse("01/01/2017")
todate = Date.Parse("31/01/2017")
TimeSpan = todate - fromdate
num_days = TimeSpan.Days
MsgBox(num_days)
And then I try to work out if it is a full month:
month = todate
If (month.Month = "02" And num_days = "28") Or num_days = "29" Or num_days = "30" Or num_days = "31" Or num_days = "0" Then
'do code here
Else
'do code here
End If
But this is proving to not work in February because it only sees the num_days as 27
Is there a way I can get the correct number of days between the two dates including the dates themselves being full days?
And how can I check if it is a full, correct month or not
UPDATE
The purpose of this is for a billing system so files are read into a database with from and to dates then it needs to work out the pricing from those dates.
So a product has a specific price, but first of all we need to work out whether to bill for part of a month or a full month (basically part of the product price or the full price)
So these 'Full Month' date range examples will bill the full price
Full Month:
01/01/2017 - 31/01/2017
25/01/2017 - 25/01/2017
18/01/2017 - 18/02/2017
10/01/2017 - 10/01/2018
Whereas, this date range for 'Part Month' will only bill for the number of days between the from and to date (+1 day)
Part Month
15/01/2017 - 31/01/2017
This would get what you specified:
Dim IsOneFullMonth = (d1.Day = 1 And d2 = d1.AddMonths(1).AddDays(-1))
Dim IsOnMonthLater = (d2 = d1.AddMonths(1))
The two states are not really the same thing in my understanding.
The second check is one month and one day.
(The first would match 'Jan 01 - Jan 31', the second one 'Jan 01 - Feb 01'.)
Also consider that neither check would match 'end of months' like 2016-02-29 - 2016-03-31 - you have to really define what you want to achieve in those cases.

Day360 in vb.net

I want to use the Days360 function in VB.Net. I need to know the difference in days between two dates assuming 360 days in a year (not 365 days the DateDiff function uses).
For example DateDiff(DateInterval.Day,"16/10/2015", "04/02/2016") = 111 days, but Days360 should return 109 days.
Days360 function in Excel calculates the days between two dates using a fictional calendar that has 30 days in each month. This method is used for some financial purposes.
You can write a function to do the same calculation.
[Edit]
Excel supports two versions of the calculation: one common in the US (this is the default) and the other common in Europe (see the documentation of the DAYS360 function for details).
The code I originally posted implemented the European version. I have updated it to support both versions. Thanks to Nikhil Vartak for pointing this out.
Function Days360(startDate As DateTime, endDate As DateTime, euMethod As Boolean) As Integer
Dim months As Integer = (endDate.Year - startDate.Year) * 12 + endDate.Month - startDate.Month
If euMethod Then
'Use European method (start or end dates after the 30th of the month are changed to 30th)
Return months * 30 + Math.Min(30, endDate.Day) - Math.Min(30, startDate.Day)
Else 'Use US method
'If the start date is the last day of the month, change it to the 30th
Dim startDay As Integer = startDate.Day
startDay = If(startDate.Day >= DateTime.DaysInMonth(startDate.Year, startDate.Month), 30, startDate.Day)
'If end date is last of the month, change it to the 30th
Dim endDay As Integer = endDate.Day
endDay = If(endDate.Day >= DateTime.DaysInMonth(endDate.Year, endDate.Month), 30, endDate.Day)
'If end date is last of the month and start date is before 30th, change end date to 1st of the next month
If endDate.Day >= DateTime.DaysInMonth(endDate.Year, endDate.Month) And startDay < 30 Then
endDay = 1
months += 1
End If
Return months * 30 + endDay - startday
End If
End Function

Excel VBA Comparing between a given date and (given date - 2 months)

I am writing a code to ensure that the data date of a system is not later than 2 business month-end date. For instance, if the job run date for the system is 23/12/2015, the valid data date is 30/10/2015 and 30/11/2015. The dates involved are only business days.
I have this code below:
If DateDiff("m", dataDate, jobRunDate) > 2 Then
MsgBox "Error in dataDate"
End If
However, I do not know how to find:
The last day of the month
Compute 2 business month back
Any help will be greatly appreciated. Thanks!
To find the last day of the month, you can find the first day of the next month and subtract a day:
Dim last As Date
Dim current As Date
current = Now
last = DateSerial(Year(current), Month(current), 1) - 1
Debug.Print last
To get the last business day of a month, just subtract days until it falls on a weekday:
Do While Weekday(last, vbMonday) > 5
last = last - 1
Loop
Debug.Print last
Combining the 2 ideas and extracting it as a function gets you this:
Private Sub Example()
Debug.Print LastBizDayOfMonth(Year(Now), Month(Now) - 1)
Debug.Print LastBizDayOfMonth(Year(Now), Month(Now) - 2)
End Sub
Private Function LastBizDayOfMonth(inYear As Integer, inMonth As Integer) As Date
LastBizDayOfMonth = DateSerial(inYear, inMonth + 1, 1) - 1
Do While Weekday(LastBizDayOfMonth, vbMonday) > 5
LastBizDayOfMonth = LastBizDayOfMonth - 1
Loop
End Function
Here is how to get the last day of a month:
Sub LastDayOfMonth()
Dim d As Date
mnth = 12
yr = 2015
d = DateSerial(yr, mnth + 1, 0)
MsgBox d
End Sub
You must then subtract two months from that date. If the result falls on a Saturday or Sunday, you must decide if you want to go forward to the next Monday or backward to the previous Friday.