You can use the following basic syntax in VBA to insert a timestamp into a particular cell in Excel:
Sub InsertTimestamp()
Range("A1").Value = Format(Now, "mm/dd/yyyy hh:mm:ss")
End Sub
This particular macro inserts the current time formatted as mm/dd/yyyy hh:mm:ss into cell A1.
Note: The Now function in VBA returns the current date and time according to your computer’s system date and time.
The following example shows how to use this syntax in practice.
Example: How to Insert Timestamp Using VBA
Suppose we create the following macro to insert the current date and time as a timestamp into cell A1 of our current sheet in Excel:
Sub InsertTimestamp()
Range("A1").Value = Format(Now, "mm/dd/yyyy hh:mm:ss")
End Sub
When we run this macro, we receive the following output:
Cell A1 now displays the current date and time when this macro was run.
For this particular example, the datetime is formatted as mm/dd/yyyy hh:mm:ss.
Note that we could also specify a different format to use.
For example, we could create the following macro to display the current time in the format dd-mm-yyyy hh:mm:ss in cell B1:
Sub InsertTimestamp()
Range("A1").Value = Format(Now, "mm/dd/yyyy hh:mm:ss")
Range("B1").Value = Format(Now, "dd-mm-yyyy hh:mm:ss")
End Sub
When we run this macro, we receive the following output:
Cells A1 and B1 now both display the current date and time in different formats.
Note: You can find the complete documentation for the Format function in VBA here.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
How to Compare Dates in VBA
How to Format Time in VBA
How to Calculate Time Difference in VBA