VBA get the last day of the month - vba

I am pretty new to VBA. I have a range of dates and I need to write a code that will change the date in the cell to the last day of the month, used in a cell.
For example, if the date in the cell is 28/03/2018 I want it to be replaced by 31/03/2018. Any idea how I can do that?

You can also get the result you need with one line of code thanks to the Eomonth formula:
Range("A1") = Excel.Application.WorksheetFunction.EoMonth(Range("A1").Value2, 0)

You can use a user-defined function GetLastDayOfMonth() and pass the range you are interested in:
Option Explicit
Public Function GetLastDayOfMonth(ByVal myDate As Date) As Date
GetLastDayOfMonth = DateSerial(Year(myDate), Month(myDate) + 1, 0)
End Function
Public Sub TestMe()
Range("A1") = DateSerial(2000, 11, 11)
If Range("A1") = GetLastDayOfMonth(Range("A1")) Then
Debug.Print "LAST DAY!"
End If
Range("A1") = DateSerial(2000, 12, 31)
If Range("A1") = GetLastDayOfMonth(Range("A1")) Then
Debug.Print "LAST DAY! " & Range("A1")
Range("A1") = DateAdd("d", 1, Range("A1"))
End If
End Sub
The function checks the month and the year of the date, which is passed and it returns a new date, which is the last day of the month for this specific month and year.
Then in the TestMe version, you can compare a given date with the last day of the month, generated by the function. If the dates are the same, then this date is the last day of the corresponding month. Using DateAdd() it is possible to get the next day of the lastDay.
In the example above, I have explicitly written Range("A1") 9 times, thus it is probably easier to follow.

To get it really short you can use:
Sub test()
Dim myDate As Date
myDate = #3/28/2018#
Debug.Print DateSerial(Year(myDate), Month(myDate) + 1, 0)
End Sub

First, if you just want the last day of the month in Excel, use the =EOMONTH function, or see this SO post for the vba code:
VBA Run Macro Last Day of the Month
Rolling your own date time code is a bad idea. Don't do it.

This VBA function will calculate the last day of the month:
Public Function LastDay(ByVal d As Date)
Dim returnDate As Date
'First day of current month
returnDate = DateSerial(Year(d), Month(d), 1)
'Forward a month
returnDate = DateAdd("m", 1, returnDate)
'back one day
returnDate = DateAdd("d", -1, returnDate)
LastDay = returnDate
End Function
Works by jumping to the beginning of the month, adding a month then subtracting a day (so 1st Feb->1st Mar->28 Feb)

Like this in VBA:
Sub LastDayOfMonth()
Dim dates As Range, dt As Range
Set dates = Range("A1") //Update as required
For Each dt In dates
dt = Application.WorksheetFunction.EoMonth(dt, 0) //e.g. 01/06/2018 ~~~> 30/06/2018
Next
End Sub

VBA way:
Function LastDayOfMonth(ByVal d As Date)
LastDayOfMonth = DateSerial(Year(d), Month(d), 1)
LastDayOfMonth = DateAdd("m", 1, LastDayOfMonth)
LastDayOfMonth = DateAdd("d", -1, LastDayOfMonth)
End Function
Construct new date:
year: from old date
month: from old date
day: 1
Add 1 month to new date.
Subtract 1 day from new date.
Steps 2 and 3 save you from all complexities of date calculations.
For Excel way, please refer to the other answer.

Related

How can I find the time number of days between a given date, and the given date's first day of the year in VBA?

For example, the inputted date is 2001/01/21 the output must be 21 because 21 days passed since the inputted date's first day of the year.
Transform the date to a value and do the same for the "new" date? Do the same in Dev.mode newCelldate.Value - yearStartdate.Value?
Copy and paste the following to your VB Editor. Then, run the "TestNumberOfDays" procedure.
Function FirstDayOfTheGivenYear(pDate As Date)
'this will return first day of the given year
FirstDayOfTheGivenYear = 1 * (CDate(pDate) - DatePart("y", CDate(pDate) - 1))
End Function
Function YTDDays(pDate As Date) As Long
'this will find the day differences between two dates
YTDDays = DateDiff("d", FirstDayOfTheGivenYear(pDate), pDate) + 1
End Function
Sub TestNumberOfDays()
'change the date according to your need
MsgBox (YTDDays("2001/01/30"))
End Sub
Like this:
InputDate = #2001/01/21#
OrdinalDay = DatePart("y", InputDate)

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.

Visual Basic: Calculating days until birthday from today

I need to make a function what calculates days until birthday from todays date.
What I have so far is:
Function synnipaev(sk As Date, tana As Date)
synnipaev = DateDiff("d", sk, tana)
End Function
sk is birthdate in the Excel sheet (formated as 10.10.2001 DD/MM/YYYY)
tana is todays date in the Excel sheet ( =TODAY() DD/MM/YYYY)
It gives me the days but also includes the years.
How to make the function not include years?
DateDiff is simply giving you the total number of days between the two dates. You need to find the difference between the current date and the next birthdate:
Public Function DaysToBirthday(birthday As Date) As Integer
Dim targetYear As Integer
'Has the birthday already passed this year?
If Month(Now) > Month(birthday) Or _
(Month(Now) = Month(birthday) And Day(Now) > Day(birthday)) Then
'Then use next year.
targetYear = Year(Now) + 1
Else
targetYear = Year(Now)
End If
DaysToBirthday = CInt(DateSerial(targetYear, Month(birthday), Day(birthday)) - Now)
End Function
Note: VBA stores Date variables as Doubles, with days to the left of the decimal and time to the right. If all you care about are days, you can save the function call and do a simple subtraction.

How to get starting date in a Week based on week number using vb.net?

I need help on getting the starting date of a week from a given week number in vb.net.
I have combobox binded with items 1-53 as week numbers. What I want to do is whenever I select a specific week number, it will return the first date of that selected week number.
For instance I have selected week Number 46, it must return November 11, 2013 as first date of week number 46.
I have tried the following codes and it returns only the first date of a week from a current week number.
DateAdd("d", -Weekday(Now, FirstDayOfWeek.Monday) + 1, Now)
Is there any possible way that can return my expected output?
Please help me. Thanks in advance.
Public Function FirstDateOfWeek(ByVal Year As Integer, ByVal Week As Integer, Optional FirstDayOfWeek As DayOfWeek = DayOfWeek.Monday) As Date
Dim dt As Date = New Date(Year, 1, 1)
If dt.DayOfWeek > 4 Then dt = dt.AddDays(7 - dt.DayOfWeek) Else dt = dt.AddDays(-dt.DayOfWeek)
dt = dt.AddDays(FirstDayOfWeek)
Return dt.AddDays(7 * (Week - 1))
End Function
You could try something like this:
Private Sub TestDateAdd()
Dim weekStart As DateTime = GetWeekStartDate(46, 2013)
Console.WriteLine(weekStart)
End Sub
Private Function GetWeekStartDate(weekNumber As Integer, year As Integer) As Date
Dim startDate As New DateTime(year, 1, 1)
Dim weekDate As DateTime = DateAdd(DateInterval.WeekOfYear, weekNumber - 1, startDate)
Return DateAdd(DateInterval.Day, (-weekDate.DayOfWeek) + 1, weekDate)
End Function
Disclaimer: I only really tested this with the one input, you probably want to make sure that it works as expected for different years, etc..

How to loop through the weeks in a date range with vba

I have seen how to loop through weeks of a year, w1301,w1302,w1303, I can get the week number if i loop through + on week number but I believe there is a way to directly loop weekly with vba, i hope at least.
DateSerial(Year(Now), Month(Now), Day(Now)) To DateSerial(2013, 3, 1)
StartDate = #1/1/2013#
EndDate = #12/31/2013#
For DateLooper = StartDate To EndDate
I got the function for a week number from date
Public Function IsoWeekNumber(d1 As Date) As Integer
Attributed to Daniel Maher
Dim d2 As Long
d2 = DateSerial(Year(d1 - WeekDay(d1 - 1) + 4), 1, 3)
IsoWeekNumber = Int((d1 - d2 + WeekDay(d2) + 5) / 7)
End Function
You could just use the DateAdd function
For i = 1 To 52
Debug.Print DateAdd("ww", i, Now())
Next i
A day has an integer value of 1, so you could iterate by week like this:
startDate = #1/1/2013#
endDate = #12/31/2013#
For d = startDate To endDate Step 7
'do stuff
Next
The week number can be determined with the DatePart function, e.g.:
WScript.Echo DatePart("ww", Now)
This will work in both vbscript and vba.
I tried this solution and it seems to work, am not 100% sure of how it handles the 28,30,31 days of different months but i trust vba. i know am making a mistake probably :))
currentDate = "2013-01-02" ' coz i wanted to start on a wednesday
for week = 1 to 52
debug.print currentDate
currentDate = DateAdd("ww",1,currentDate)
next week