简体   繁体   English

从出生日期计算年龄的VBA公式

[英]VBA formula to calculate Age from Born Date

I have Born Dates and want apply this formula我有出生日期并想应用这个公式

=(YEAR(NOW())-YEAR(A2))

in VBA for calculate age for whole row of dates在 VBA 中计算整行日期的年龄

for example例如

      A           B
1  BornDate      Age
2  09.06.1991    28
3  02.07.1973
4
5

my code works only for first two and stop without any error.我的代码仅适用于前两个并且停止而没有任何错误。

Sub btn_GetAge()

    Dim LastRow As Long

    With ThisWorkbook.Worksheets("Sheet1")
    LastRow = .Cells(.Rows.Count).End(xlUp).Row
    .Range("B2:B" & LastRow) = "=(YEAR(NOW())-YEAR(A1))"
    End With

End Sub

Any idea or choose different formula ?任何想法或选择不同的公式?

1) Cells requires a row and column, eg A1 is Cells(1,1) 1) Cells 需要一行和一列,例如 A1 是 Cells(1,1)

2) Your formula (and better to specify the property) starts in row 2 but refers to A1 2)您的公式(最好是指定属性)从第 2 行开始,但指的是 A1

Sub btn_GetAge()

Dim LastRow As Long

With ThisWorkbook.Worksheets("Sheet1")
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    .Range("B2:B" & LastRow).Formula = "=(YEAR(NOW())-YEAR(A2))"
End With

End Sub

You were very close:你非常接近:

Sub btn_GetAge()

    Dim LastRow As Long

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
        .Range("B2:B" & LastRow) = "=YEAR(TODAY())-YEAR(A2)"
    End With

End Sub

在此处输入图片说明

Try:尝试:

Option Explicit

Sub Test()

    Dim Lastrow As Long, i As Long
    Dim CurrenctYear As Long, LoopYear As Long

    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
            CurrenctYear = Year(Now)

        For i = 1 To Lastrow
            LoopYear = Year(.Range("A" & i).Value)
            .Range("A" & i).Offset(0, 1).Value = CurrenctYear - LoopYear
        Next i

    End With

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM