我错过的错误在哪里?
Where is the error I am missing?
如果当年未命中出生日期,则此子将无法正确计算。如果 DOB 是 1950 年 12 月 31 日,它会将 DOB 计算为 56,但此人在 12 月 31 日之前实际上是 55 岁。有没有我可以添加的更新来适应这个。
Sub EE_DatedIf_ButtonC_()
Dim wb1 As Workbook
Dim i As Long
Dim LastRow1 As Long
Dim yrDiff As Long
Dim d1 As Date
Dim d2 As Date
Set wb1 = Workbooks("macro all client v.01.xlsm")
LastRow1 = wb1.Sheets("Carrier").range("F:F").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
For i = 10 To LastRow1
d1 = wb1.Sheets("Carrier").Cells(8, 1)
d2 = wb1.Sheets("Carrier").Cells(i, 24)
yrDiff = DateDiff("yyyy", d2, d1)
wb1.Sheets("Carrier").Cells(i, 3) = yrDiff
Next i
End Sub
如果您取月差数,将该数字除以 12 并截断会怎么样
yrDiff = CInt(DateDiff("m", d2, d1) / 12)
或者更准确地说,对小时数做同样的事情
yrDiff = CInt(DateDiff("h", d2, d1) / 8766)
UPDATE CInt
将舍入,而不是截断。在此处使用此功能
Public Function Trunc(ByVal value As Double, ByVal num As Integer) As Double
Trunc = Int(value * (10 ^ num)) / (10 ^ num)
End Function
然后这样称呼它
yrDiff = Trunc(DateDiff("h", d2, d1) / 8766, 0)
如果您比较相同的 month/day 以确定该日期是否已过,您将得到 True 或 False。在 VBA 中,True 为 -1,False 为 0,因此您可以在日期已经过去时简单地添加(通过减去)
Sub test()
Dim d1 As Date, d2 As Date
Dim yrDiff As Long
d2 = #5/31/1950#
d1 = #6/30/2016#
yrDiff = Year(d1) - Year(d2) + CLng(d1 < DateSerial(Year(d1), Month(d2), Day(d2)))
Debug.Print yrDiff
d2 = #7/31/1950#
yrDiff = Year(d1) - Year(d2) + CLng(d1 < DateSerial(Year(d1), Month(d2), Day(d2)))
Debug.Print yrDiff
End Sub
如果当年未命中出生日期,则此子将无法正确计算。如果 DOB 是 1950 年 12 月 31 日,它会将 DOB 计算为 56,但此人在 12 月 31 日之前实际上是 55 岁。有没有我可以添加的更新来适应这个。
Sub EE_DatedIf_ButtonC_()
Dim wb1 As Workbook
Dim i As Long
Dim LastRow1 As Long
Dim yrDiff As Long
Dim d1 As Date
Dim d2 As Date
Set wb1 = Workbooks("macro all client v.01.xlsm")
LastRow1 = wb1.Sheets("Carrier").range("F:F").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
For i = 10 To LastRow1
d1 = wb1.Sheets("Carrier").Cells(8, 1)
d2 = wb1.Sheets("Carrier").Cells(i, 24)
yrDiff = DateDiff("yyyy", d2, d1)
wb1.Sheets("Carrier").Cells(i, 3) = yrDiff
Next i
End Sub
如果您取月差数,将该数字除以 12 并截断会怎么样
yrDiff = CInt(DateDiff("m", d2, d1) / 12)
或者更准确地说,对小时数做同样的事情
yrDiff = CInt(DateDiff("h", d2, d1) / 8766)
UPDATE CInt
将舍入,而不是截断。在此处使用此功能
Public Function Trunc(ByVal value As Double, ByVal num As Integer) As Double
Trunc = Int(value * (10 ^ num)) / (10 ^ num)
End Function
然后这样称呼它
yrDiff = Trunc(DateDiff("h", d2, d1) / 8766, 0)
如果您比较相同的 month/day 以确定该日期是否已过,您将得到 True 或 False。在 VBA 中,True 为 -1,False 为 0,因此您可以在日期已经过去时简单地添加(通过减去)
Sub test()
Dim d1 As Date, d2 As Date
Dim yrDiff As Long
d2 = #5/31/1950#
d1 = #6/30/2016#
yrDiff = Year(d1) - Year(d2) + CLng(d1 < DateSerial(Year(d1), Month(d2), Day(d2)))
Debug.Print yrDiff
d2 = #7/31/1950#
yrDiff = Year(d1) - Year(d2) + CLng(d1 < DateSerial(Year(d1), Month(d2), Day(d2)))
Debug.Print yrDiff
End Sub