This macro counts the number of years between the first and last date of a work experience. I made this work but getting this number in a weird format (Like a Date instead of a number). Looks like that something might be wrong. Thanks in advance for your comments.
Sub CuentaExperiencia()
Worksheets("Candidatos").Activate
'esta macro contabiliza los años de experiencia sumados
Range("T2").Select
Do Until ActiveCell.Offset(0, -18).Value = ""
If ActiveCell.Value = "" Then
ActiveCell.FormulaR1C1 = DateDiff("d", (ActiveCell.Offset(0, -2)), (ActiveCell.Offset(0, -1)))
End If
ActiveCell.Offset(1, 0).Select
Loop
Range("AE2").Select
Do Until ActiveCell.Offset(0, -29).Value = ""
If ActiveCell.Value = "" Then
ActiveCell.FormulaR1C1 = DateDiff("d", (ActiveCell.Offset(0, -2)), (ActiveCell.Offset(0, -1)))
End If
ActiveCell.Offset(1, 0).Select
Loop
Range("AP2").Select
Do Until ActiveCell.Offset(0, -40).Value = ""
If ActiveCell.Value = "" Then
ActiveCell.FormulaR1C1 = DateDiff("d", (ActiveCell.Offset(0, -2)), (ActiveCell.Offset(0, -1)))
End If
ActiveCell.Offset(1, 0).Select
Loop
Range("BA2").Select
Do Until ActiveCell.Offset(0, -51).Value = ""
If ActiveCell.Value = "" Then
ActiveCell.FormulaR1C1 = DateDiff("d", (ActiveCell.Offset(0, -2)), (ActiveCell.Offset(0, -1)))
End If
ActiveCell.Offset(1, 0).Select
Loop
End Sub
Just use the =DAYS(end_date,start_date)
formula, and then divide by 365 to get the number of years; no need to use VBA. If you are doing it as part of a larger VBA macro, you can just use WorksheetFunction.Days(end_date,start_date)
.
EDIT: Even easier: just use =YEARFRAC()
. It'll do it all for you.
You should note that simply dividing by 365 does not account for leap years, which introduces some error into the answer. While this error is trivial in this case, you may avoid it simply by using =YEARFRAC(start_date, end_date, [basis])
, and using 1
as the basis parameter. This will force the use of actual calendar days, which will account for leap year correctly. Otherwise, YEARFRAC
assumes a standard 30-day month for every month, and your answer will be increasingly inexact.