VBA provides three functions enabling you to determine the current date and time set in your computer’s hardware. These functions—Now, Date, and Time—check your system clock and return all or part of the current setting. None of these functions require any parameters, and they can be summarized simply:
Function | Return Value |
Now | Returns the current date and time |
Date | Returns the date portion of the current date and time |
Time | Returns the time portion of the current date and time |
Although these functions seem somewhat redundant, they do each have their purpose. For example, if you want to display only the current time without the date portion, it’s simpler to call the Time function than to call the Now function and remove the date portion.
You can use the Date and Time statements to set the current date and time as well. Placing either keyword on the left-hand side of an equal sign allows you to assign a new value to the system date and time.
For example, the following fragment checks the current time, and if it’s past 1:00 p.m., executes some code.
If Time > #1:00 PM# Then
' Only execute this code if it’s after 1 PM.
End if
On the other hand, the following comparison wouldn’t make any sense in this context because the value in Now (a value like 34565.2345) is guaranteed to be greater than #1:00 PM# (the value 0.5416666667):
If Now > #1:00 PM# Then
' Only execute this code if it's after 1 PM.
End if
Unlike other functions, Now, Date, and Time don’t require trailing parentheses. In fact, if you enter the parentheses, VBA often politely removes them for you.