VBA DatePart function

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

DatePart Function Description

The VBA DatePart function returns a component the specified date e.g. year, month, second etc.

The DatePart function can well be superseded by other Date functions such as Year, Month and similar functions (see full list of Date functions above).

Syntax

The syntax for the DatePart function in VBA is:

DatePart( interval, date, [firstdayofweek], [firstweekofyear] )

Parameters

interval
A string which defines the type of date/time interval which will be returned for the specified date. The following are acceptable interval string types:

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

date
The date for which the interval component is to be returned.

firstdayofweek
Optional. A constant that specifies the first day of the week. If omitted, assumes that Sunday is the first day of the week. Can be one of the following VBA constants:

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

firstweekofyear
Optional. It is a constant that specifies the first week of the year. If this parameter is omitted, it assumes that the week containing Jan 1st is the first week of the year. This parameter can be one of the following values:

VBA Constant Value Description
vbUseSystem 0 Use the system setting
vbFirstJan1 1 Use the first week that includes Jan 1st (default)
vbFirstFourDays 2 Use the first week in the year that has at least 4 days
vbFirstFullWeek 3 Use the first full week of the year

Other Notes

The DatePart function can well be replaced by other Date functions. See examples below:

Year "2015/02/01"
'Result: 2015

Month "2015/02/01"
'Result: 2

Hour "2015/02/01 10:20"
'Result: 10

Example usage

The DatePart function can be used in VBA code. Let’s look at some VBA DatePart function examples:

DatePart "yyyy", "2015/02/01"
'Result: 2015 (year)

DatePart "m", "2015/02/01"
'Result: 2 (month)
DatePart "n", "2015/02/01 10:20"
'Result: 20 (minutes)

Simply the best place to learn Excel VBA