Excel VBA Classic Excel VBA 2010 Excel VBA 365 Excel VBA Examples About Us

Lesson 11: Date and Time Functions


Excel VBA provides various built-in date and time functions that allows us to write VBA codes involving dates and times. We can use date and time functions to display system date and time , add and substract data and time, converting string to date and more. 

11.1 Date and Time Functions.

The date and time functions are explained in Table 11.1.

Table 11.1 Date and Time Functions
FunctionDescription
Nowreturns current system date and time
Datereturns current system date
Day(Date)Returns the day of the month for the date specified in the argument
Weekday(Date)Returns weekday as an integer for the date specified in the argument
WeekdayName(Weekday(Date))Returns the name of weekday for the date specified in the argument
WeekdayName(Weekday(Date),True)Returns the abbrieviated name of weekday for the date specified in the argument
Month(Date)Returns the month of the year in integer for the date specified in the argument
MonthName(Month(Date))Returns the name of month of the year for the date specified in the argument
MonthName(Month(Date))Returns the abbrieviated name of month of the year for the date specified in the argument
Year(Date)Returns the year in integer for the date specified in the argument

Example 11.1

Private Sub CommandButton1_Click()
 Cells(1, 2) = Now
 Cells(2, 2) = Date
 Cells(3, 2) = Day(Date)
 Cells(4, 2) = Weekday(Date)
 Cells(5, 2) = WeekdayName(Weekday(Date))
 Cells(6, 2) = WeekdayName(Weekday(Date), "true")
 Cells(7, 2) = Month(Date)
 Cells(8, 2) = MonthName(Month(Date))
 Cells(9, 2) = MonthName(Month(Date), "true")
 Cells(10, 2) = Year(Date)
End Sub

The output is as shown in Figure 11.1

Figure 11.1

11.2 Time, Hour, Minute, Second and Timer Functions

The time functions are explained in Table 11.2.

Table 11.2 Time Functions
FunctionDescription
TimeReturns the current system time
Hour(time)Returns the hour from its argument
Minute(time)Returns the minute from its argument
Second(time)Returns the second from its argument
TimerReturns the number of seconds since midnight

Example 11.2

Private Sub CommandButton1_Click()

Cells(1, 2) = Time
Cells(2, 2) = Hour(Time)
Cells(3, 2) = Minute(Time)
Cells(4, 2) = Second(Time)
Cells(5, 2) = Timer

End Sub

Figure 11.2


❮ Previous Lesson Next Lesson ❯


Copyright ® 2008 Dr.Liew Voon Kiong . All rights reserved   [Privacy Policy]

Contact: Facebook Page