我有出生日期,想应用此公式
media
在VBA中用于计算整行日期的年龄
例如
=(YEAR(NOW())-YEAR(A2))
我的代码仅适用于前两个代码,并且停止运行不会出现任何错误。
A B
1 BornDate Age
2 09.06.1991 28
3 02.07.1973
4
5
有什么想法或选择其他公式吗?
答案 0 :(得分:4)
1)单元格需要一行和一列,例如A1是Cells(1,1)
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
答案 1 :(得分:3)
您非常亲密:
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
答案 2 :(得分:1)
尝试:
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