Data type Date are stored as IEEE 64-bit (8-byte) ranging from 1 January 100, to 31 December 9999, and times from 0:00:00 to 23:59:59. The Date uses decimal numbers to represent the date and time together therefore our result must be declare as Double.
VBA Vode: (To get different date in Hours, Days, Months and Years)
Sub Examples_DateDiffer()
Dim DtNumA As Date, DtNumB As Date
Dim DtNumHr As Long, DtNumDy As Long
Dim DtNumMn As Long, DtNumYr As Integer
DtNumA = "16-10-2022": DtNumB = "16-10-2021"
If DtNumA - DtNumB > 0 Or DtNumA - DtNumB < 0 Then
DtNumHr = DateDiff("H", DtNumB, DtNumA) 'Different in Hours
DtNumDy = DateDiff("D", DtNumB, DtNumA) 'Different in Days
DtNumMn = DateDiff("M", DtNumB, DtNumA) 'Different in Months
DtNumYr = DateDiff("YYYY", DtNumB, DtNumA) 'Different in Years
Else
MsgBox "Sorry! Same date compare.TQ"
Exit Sub
End If
Debug.Print "Hours: " & DtNumHr, "Days: " & DtNumDy, _
"Months: " & DtNumMn, "Years: " & DtNumYr
End Sub
Answer: Hours: 8760 Days: 365 Months: 12 Years: 1
VBA Vode: (To get date after add Days, Months and Years)
Sub Examples_DateAdded()
Dim DtBefore As Date, DtAfterDy As Date
Dim DtAfterMn As Date, DtAfterYr As Date
DtBefore = DateValue("Oct 16, 2022")
DtAfterDy = DateAdd("d", 3, DtBefore) 'Add 3 days after
DtAfterMn = DateAdd("m", 3, DtBefore) 'Add 3 months after
DtAfterYr = DateAdd("yyyy", 3, DtBefore) 'Add 3 years after
Debug.Print "Add 3 Days: " & DtAfterDy, "Add 3 Months: " & _
DtAfterMn, "Add 3 Years: " & DtAfterYr
End Sub
Answer: Add 3 Days: 19/10/2022 Add 3 Months: 16/1/2023 Add 3 Years: 16/10/2025
VBA Vode: (To get current date and time)
Sub Examples_DateCurrent()
Dim DtNowDef As Date, DtNowCst As String
DtNowDef = Now() 'Default
DtNowCst = VBA.Format(Now(), "mm.dd.yy hh:mm") 'Custom
Debug.Print "Default: " & DtNowDef, "Custom: " & DtNowCst
End Sub
Answer: Default: 16/10/2022 9:55:07 PM Custom: 10.16.22 21:55
(The answer base on my own time when run this code)
Note:
To converts a string to time serial number we use TimeValue function. The time's serial number is a number between 0 and 1. For example, Afternoon (half day) is represented by 0.5.
Microsoft Reference-Date-data-typeOther Reference-Date-data-type
Practice makes perfect. Thank You.
macro enabled excel
excel macro
vba coding
vba code
No comments:
Post a Comment