Return to VBA Code Examples

VBA DatePart Function

DatePart Description

Returns a specified part of a given date.

 

Simple DatePart Examples

Here is a simple DatePart example:

This code will return 2019.

 

DatePart Syntax

In the VBA Editor, you can type  “DatePart(” to see the syntax for the DatePart Function:

The DatePart function contains 4 arguments:

Interval: Time unit (Days, Months, Years, etc.). Enter as string. (ex. “m” for Month)

Setting Description
yyyy Year
q Quarter
m Month
y Day of Year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second

Date: Varient (Date) value that you want to evaluate.

FirstDayOfWeek: A constant that specifies the first day of the week. This is optional. If not specified, Sunday is assumed.

Constant Value Description
vbUseSystem 0 Use the NLS API setting.
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

FirstWeekOfYear: A constant that specifies the first week of the year. This is optional. If not specified, the first week is assumed to be the week in which January 1 occurs.

Constant Value Description
vbUseSystem 0 Use the NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default).
vbFirstFourDays 2 Start with the first week that has at least four days in the new year.
vbFirstFullWeek 3 Start with first full week of the year.

 

Examples of Excel VBA DatePart Function

Referencing Dates

To start, we will demonstrate different ways to reference dates using the VBA DatePart Function.

Each of these DatePart functions produce the same result:

Or you can reference a cell containing a date:

Or create and reference date variables:

 

Using Different Units of Interval

Quarter

Month

Day

Week

Hour

Minutes

Second

 

 

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as


Learn More!