VBA Function: DatePart
The VBA function DatePart returns an integer value corresponding to a specific part of a date (day, month, year, hour, minute, second, day of the week, and week number).
Usage:
DatePart(date_part, date)
Example of Usage
Using the DatePart function to retrieve different data from a date:
Sub example()
myDate = #10/25/2024 3:35:45 PM#
'Day (1 to 31)
MsgBox DatePart("d", myDate) 'Returns: 25
'Day of the year (1 to 366)
MsgBox DatePart("y", myDate) 'Returns: 299
'Hour
MsgBox DatePart("h", myDate) 'Returns: 15
'Minute
MsgBox DatePart("n", myDate) 'Returns: 35
'Second
MsgBox DatePart("s", myDate) 'Returns: 45
'Month
MsgBox DatePart("m", myDate) 'Returns: 10
'Year
MsgBox DatePart("yyyy", myDate) 'Returns: 2024
'Day of the week (1 to 7)
' => the 3rd argument as 2 specifies that the week starts on Monday
MsgBox DatePart("w", myDate, 2) 'Returns: 5
'Week of the year (1 to 53)
' => the 4th argument as 2 allows obtaining an ISO week number
MsgBox DatePart("ww", myDate, , 2) 'Returns: 43
End Sub