一、符合如下的條件
1歲以上寫歲
1月以上寫月,
不足月寫天。
二、宏代碼
Function GetDateDiff(StartD, EndD)
Dim y%, m%, d%
If StartD > EndD Or Not IsDate(StartD) Or Not IsDate(EndD) Then GetDateDiff = "數據有誤"
y = DateDiff("yyyy", StartD, EndD)
If DateSerial(Year(EndD), Month(StartD), Day(StartD)) > EndD Then
y = y - 1
If y >= 1 Then GoTo 100
m = 12 - Month(StartD) + Month(EndD)
Else
m = Month(EndD) - Month(StartD)
End If
If Day(EndD) >= Day(StartD) Or Day(EndD) = Day(DateSerial(Year(EndD), Month(EndD) + 1, 0)) Then
If Day(EndD) >= Day(StartD) Then d = Day(EndD) - Day(StartD)
If Day(EndD) < Day(StartD) And Day(EndD) = Day(DateSerial(Year(EndD), Month(EndD) + 1, 0)) Then d = Day (DateSerial(Year(StartD), Month(StartD) + 1, 0)) - Day(StartD)
Else
m = m - 1
d = Day(DateSerial(Year(StartD), Month(StartD) + 1, 0)) - Day(StartD) + Day(EndD)
End If
If m >= 1 Then d = 0
100: GetDateDiff = IIf(y > 0, y & "歲", IIf(m > 0, m & "月", d & "天"))
End Function
Sub Get年月日()
Dim arr1, arr2()
arr = Sheet1.Range("a2:b" & Sheet1.Range("A65536").End(xlUp).Row)
ReDim arr2(1 To UBound(arr), 1 To 1)
For i = 1 To UBound(arr)
arr2(i, 1) = GetDateDiff(arr(i, 1), arr(i, 2))
Next i
Sheet1.Range("C2:c" & Sheet1.Range("A65536").End(xlUp).Row) = arr2
End Sub
以上代碼是宏代碼,在模塊中使用。