Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get start and end of previous month in VB

Tags:

vba

ms-access

Im trying to create some VB code that will get the start and end of the previous month. Im able to the current month which is just:

Month(DateValue(Now))

which would return 3. From there I can take away 1 to give me 2 meaning February. This is fine but what about when I Im in January and I repeat this and it gives me zero - my code will fail. Any one know how to get the previous months start and end day then?

Thanks

like image 555
Katana24 Avatar asked Mar 15 '13 10:03

Katana24


2 Answers

The first day of the previous month is always 1, to get the last day of the previous month, use 0 with DateSerial:

''Today is 20/03/2013 in dd/mm/yyyy
DateSerial(Year(Date),Month(Date),0) = 28/02/2013 
DateSerial(Year(Date),1,0) = 31/12/2012 

You can get the first day from the above like so:

LastDay = DateSerial(Year(Date),Month(Date),0)
FirstDay = LastDay-Day(LastDay)+1

See also: How to caculate last business day of month in VBScript

like image 55
Fionnuala Avatar answered Oct 07 '22 16:10

Fionnuala


firstDay = DateSerial(Year(DateAdd("m", -1, Now)), Month(DateAdd("m", -1, Now)), 1)
lastDay = DateAdd("d", -1, DateSerial(Year(Now), Month(Now), 1))

This is another way to do it, but I think Remou's version looks cleaner.

like image 31
MrBlue Avatar answered Oct 07 '22 15:10

MrBlue