Day of the week and other day and week related functions in VBA
This page shows the code for commonly used date functions and code fragments which involve a days and weeks:
- Day of the week - 1 = sunday
- Day of the month - 31
- Name of WeekDay - Tuesday - or abbreviated
- Today, Yesterday or Tomorrow
- Next and previous day
Day of the week
The Weekday
function returns the daynumber while starting to count from the first day of the week that you specified. If not specified, vbSunday (=1) is assumed.
So, in this case, if the returned value is 3 (=vbTuesday) it is Tuesday.
Dim dtDate As Date: dtDate =
Dim iWeekday As Integer
iWeekday = Weekday(Date:=dtDate, FirstDayOfWeek:=vbSunday)
Name of WeekDay - WeekDayName
Returns localized WeekDay name. On Eglish systems returns Tuesday
for the 3rd WeekDay.
By setting Abbreviate:=True
you will get the abbreviation, in this case Tue
Dim lngWeekDay As Long: lngWeekDay = 3
Dim strWeekDayName As String
strWeekDayName = WeekdayName(Weekday:=lngWeekDay, Abbreviate:=False, FirstDayOfWeek:=vbSunday)
Today
To get today's date, simply call the Date
function
Dim dtToday As Date
dtToday = Date
Next day
The vba code fragment below calculates the next day from the date that was given as input.
As an example with dt = #12/21/2022#
will return 12/22/2022
Dim dtNextDay As Date
Dim dt As Date: dt = #12/21/2022#
dtNextDay = DateAdd("d", 1, dt)
Tomorrow
Tomorrow can simply be calculated by substituting the Date (=ToDay) function as the value for the date argument:
Dim dtTomorrow As Date
dtTomorrow = DateAdd(Interval:="d", Number:=1, Date:=Date)
Previous day
The vba code fragment below calculates the next day from the date that was given as input.
As an example with dt = #12/21/2022#
will return 12/22/2022
Dim dtNextDay As Date
Dim dt As Date: dt = #12/21/2022#
dtNextDay = DateAdd("d", 1, dt)
Yesterday
Yesterday can simply be calculated by substituting the Date (=ToDay) function as the value for the date argument:
Dim dtYesterday As Date
dtYesterday = DateAdd(Interval:="d", Number:=-1, Date:=Date)