Friday, August 12, 2016

How to use the DATEPART Function (VBA)

Description

The Microsoft Excel DATEPART function returns a specified part of a given date.

Syntax

The syntax for the DATEPART function in Microsoft Excel is:
DatePart( interval, date, [firstdayofweek], [firstweekofyear] )

Parameters or Arguments

interval
The interval of time that you wish to return. This parameter can be any one of the following valid interval values:
IntervalExplanation
yyyyYear
qQuarter
mMonth
yDay of year
dDay
wWeekday
wwWeek
hHour
nMinute
sSecond
date
The date value that you wish to evaluate.
firstdayofweek
Optional. It is a constant that specifies the first day of the week. If this parameter is omitted, it assumes that Sunday is the first day of the week. This parameter can be one of the following values:
ConstantValueExplanation
vbUseSystem0Use the NLS API setting
vbSunday1Sunday (default)
vbMonday2Monday
vbTuesday3Tuesday
vbWednesday4Wednesday
vbThursday5Thursday
vbFriday6Friday
vbSaturday7Saturday
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:
ConstantValueExplanation
vbUseSystem0Use the NSL API setting
vbFirstJan11Use the first week that includes Jan 1st (default)
vbFirstFourDays2Use the first week in the year that has at least 4 days
vbFirstFullWeek3Use the first full week of the year

Applies To

  • Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Function)

The DATEPART function can only be used in VBA code in Microsoft Excel.
Let's look at some Excel DATEPART function examples and explore how to use the DATEPART function in Excel VBA code:
DatePart("yyyy", "15/10/2012")
Result: 2012

DatePart("m", "15/10/2012")
Result: 10

DatePart("d", "15/10/2012")
Result: 15
For example:
Dim LValue As Integer

LValue = DatePart("d", "15/10/2012")
In this example, the variable called LValue would now contain the value of 15.