The VBA DatePart Function returns a part (day, month, week, etc.) of a supplied date and/or time.
The syntax of the function is:
Where the function arguments are:
Interval | - |
A string specifying the date part to be returned. This can have any of the following values:
|
||||||||||||||||||||||||||||||
Date | - | The date value that you want to return a part of. | ||||||||||||||||||||||||||||||
[FirstDayOfWeek] | - |
An optional FirstDayOfWeek enumeration value, specifying the weekday that should be used as the first day of the week. This can have any of the following values:
If omitted, the [FirstDayOfWeek] argument uses the default value vbSunday. |
||||||||||||||||||||||||||||||
[FirstWeekOfYear] | - |
An optional FirstWeekOfYear enumeration value, specifying the week that should be used as the first week of the year. This can have any of the following values:
If omitted, the [FirstWeekOfYear] argument uses the default value vbFirstJan1. |
' Return the day, month & year from the date 12/31/2015
Dim dy As Integer
Dim mth As Integer Dim yr As Integer
dy = DatePart( "d", #12/31/2015# )
' Now, dy = 31, mth = 12 and yr = 2015.
mth = DatePart( "m", #12/31/2015# ) yr = DatePart( "yyyy", #12/31/2015# ) |
After running the above VBA code, the variables dy, mth and yr are equal to 31, 12 and 2015, respectively.
' Return hour, minute and seconds from the time 3:05:30 PM
Dim hr As Integer
Dim min As Integer Dim sec As Integer
hr = DatePart( "h", #3:05:30 PM# )
' Now, hr = 15, min = 5 and sec = 30.
min = DatePart( "n", #3:05:30 PM# ) sec = DatePart( "s", #3:05:30 PM# ) |
After running the above VBA code, the variables hr, min and sec are equal to 15, 5 and 30, respectively.
' Return day, week & quarter info. from the date 12/31/2015
Dim dyYr As Integer
Dim dyWk As Integer Dim wkYr As Integer Dim qtr As Integer
dyYr = DatePart( "y", #12/31/2015# )
' Now, dyYr = 365, dyWk = 5, wkYr = 53 and qtr = 4.
dyWk = DatePart( "w", #12/31/2015# ) wkYr = DatePart( "ww", #12/31/2015# ) qtr = DatePart( "q", #12/31/2015# ) |
After running the above VBA code, dyYr = 365; dyWk = 5 (Thursday); wkYr = 53 and qtr = 4.
Note that the [FirstDayOfWeek] and [FirstWeekOfYear] arguments have been omitted from the above function calls and so these arguments use the default values vbSunday and vbFirstJan1 respectively.
If the Interval argument that is supplied to the VBA DatePart function is not a valid interval (i.e. is not one of the values in the above list), the DatePart function returns the error:
If the Date argument that is supplied to the VBA DatePart function cannot be recognised as a valid VBA date or time, the function returns the error: