萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Excel 教學 >> Excel 綜合

Excel 精確計算年齡:歲/月/日自動切換顯示 VBA 函數

顯示規則

  • ≥1 歲 → 顯示「X 歲」
  • ≥1 月 → 顯示「X 月」
  • <1 月 → 顯示「X 天」

VBA 自訂函數 GetDateDiff

Function GetDateDiff(StartD, EndD) As String
    Dim y As Long, m As Long, d As Long
    If StartD > EndD Or Not IsDate(StartD) Or Not IsDate(EndD) Then
        GetDateDiff = "資料有誤": Exit Function
    End If
    
    y = DateDiff("yyyy", StartD, EndD)
    If DateSerial(Year(EndD), Month(StartD), Day(StartD)) > EndD Then y = y - 1
    
    If y >= 1 Then
        GetDateDiff = y & "歲"
    Else
        m = DateDiff("m", StartD, EndD)
        If m >= 1 Then
            GetDateDiff = m & "月"
        Else
            d = DateDiff("d", StartD, EndD)
            GetDateDiff = d & "天"
        End If
    End If
End Function

批次處理巨集

Sub BatchCalcAge()
    Dim rng As Range, arr, outArr(), i As Long
    Set rng = Sheet1.Range("A2:B" & Sheet1.Cells(Rows.Count, "A").End(xlUp).Row)
    arr = rng.Value
    ReDim outArr(1 To UBound(arr, 1), 1 To 1)
    
    For i = 1 To UBound(arr, 1)
        outArr(i, 1) = GetDateDiff(arr(i, 1), arr(i, 2))
    Next
    
    Sheet1.Range("C2").Resize(UBound(arr, 1), 1).Value = outArr
End Sub

使用方式

  1. A 欄:出生日期,B 欄:基準日期(或用 Date 為今天)
  2. 執行 BatchCalcAge → C 欄自動產生年齡文字
copyright © 萬盛學電腦網 all rights reserved