VBA Function: DateAdd
The VBA function DateAdd adds the specified time interval (in seconds, minutes, hours, days, months, or years) to a date.
Usage:
DateAdd(interval, number, date)
Example of Usage
Using the DateAdd function with different time intervals:
Sub example()
myDate = #10/30/2023 3:35:45 PM#
added = 3
'Add 3 days
MsgBox DateAdd("d", added, myDate) 'Returns: 11/2/2023 3:35:45 PM
'Add 3 hours
MsgBox DateAdd("h", added, myDate) 'Returns: 10/30/2023 6:35:45 PM
'Add 3 minutes
MsgBox DateAdd("n", added, myDate) 'Returns: 10/30/2023 3:38:45 PM
'Add 3 seconds
MsgBox DateAdd("s", added, myDate) 'Returns: 10/30/2023 3:35:48 PM
'Add 3 months
MsgBox DateAdd("m", added, myDate) 'Returns: 1/30/2024 3:35:45 PM
'Add 3 years
MsgBox DateAdd("yyyy", added, myDate) 'Returns: 10/30/2026 3:35:45 PM
End Sub
If you enter the number 3.9 instead of 3, you will get the same result because the DateAdd function only considers the integer part of the number.
An alternative is to directly add the number to the date (this solution allows for decimal numbers):
Sub example()
myDate = #10/30/2023 3:00:00 PM#
added = 3.5
'Add 3.5 days
MsgBox myDate + added 'Returns: 11/3/2023 3:00:00 AM
'Add 3.5 hours
MsgBox myDate + added / 24 'Returns: 10/30/2023 6:30:00 PM
'Add 3.5 minutes
MsgBox myDate + added / (24 * 60) 'Returns: 10/30/2023 3:03:30 PM
End Sub