Cómo calcular las edades antes del 1 de enero de 1900 en Excel
Artigo
Aplícase a:
Microsoft Excel
Resumen
Aunque las fórmulas de fecha de Microsoft Excel solo pueden usar las fechas especificadas entre el 1 de enero de 1900 y el 31 de diciembre de 9999, puede usar una función personalizada de Microsoft Visual Basic para Aplicaciones para calcular la edad (en años) de alguien o algo que se creó por primera vez antes del 1 de enero de 1900.
Uso de macro para calcular la antigüedad
Microsoft proporciona ejemplos de programación con fines ilustrativos únicamente, sin ninguna garantía, ya sea expresa o implícita. Esto incluye, entre otras, las garantías implícitas de comerciabilidad e idoneidad para un fin determinado. Se considera que está familiarizado con el lenguaje de programación que se muestra y con las herramientas para crear y depurar procedimientos. Los ingenieros de soporte técnico de Microsoft pueden explicarle la funcionalidad de un determinado procedimiento, pero no modificarán estos ejemplos para ofrecer mayor funcionalidad ni crearán procedimientos adaptados a sus necesidades específicas.
Excel escribe las fechas anteriores al 1 de enero de 1900 como texto. Esta función funciona para las fechas especificadas como texto a partir de 1/1/0001, fechas normales y puede controlar las fechas en las que la fecha de inicio es anterior a 1900 y la fecha de finalización es posterior a 1900. Para usar la macro, siga estos pasos:
Inicie Excel. Vea la hoja de cálculo en la que desea usar la función.
Presione ALT+F11 para cambiar al Editor de Visual Basic.
En el menú Insertar, haga clic en Módulo.
Escriba el código siguiente en el módulo:
VB
' This is the initial function. It takes in a start date and an end date.PublicFunction AgeFunc(stdate As Variant, endate As Variant)
' Dim our variables.Dim stvar AsStringDim stmon AsStringDim stday AsStringDim styr AsStringDim endvar AsStringDim endmon AsStringDim endday AsStringDim endyr AsStringDim stmonf AsIntegerDim stdayf AsIntegerDim styrf AsIntegerDim endmonf AsIntegerDim enddayf AsIntegerDim endyrf AsIntegerDim years AsInteger' This variable will be used to modify string length.Dim fx AsInteger
fx = 0' Calls custom function sfunc which runs the Search worksheet function' and returns the results.' Searches for the first "/" sign in the start date.
stvar = sfunc("/", stdate)
' Parse the month and day from the start date.
stmon = Left(stdate, sfunc("/", stdate) - 1)
stday = Mid(stdate, stvar + 1, sfunc("/", stdate, sfunc("/", stdate) + 1) - stvar - 1)
' Check the length of the day and month strings and modify the string ' length variable.If Len(stday) = 1Then fx = fx + 1If Len(stmon) = 2Then fx = fx + 1' Parse the year, using information from the string length variable.
styr = Right(stdate, Len(stdate) - (sfunc("/", stdate) + 1) - stvar + fx)
' Change the text values we obtained to integers for calculation ' purposes.
stmonf = CInt(stmon)
stdayf = CInt(stday)
styrf = CInt(styr)
' Check for valid date entries.If stmonf < 1Or stmonf > 12Or stdayf < 1Or stdayf > 31Or styrf < 1Then
AgeFunc = "Invalid Date"ExitFunctionEndIf' Reset the string length variable.
fx = 0' Parse the first "/" sign from the end date.
endvar = sfunc("/", endate)
' Parse the month and day from the end date.
endmon = Left(endate, sfunc("/", endate) - 1)
endday = Mid(endate, endvar + 1, sfunc("/", endate, sfunc("/", endate) + 1) - endvar - 1)
' Check the length of the day and month strings and modify the string ' length variable.If Len(endday) = 1Then fx = fx + 1If Len(endmon) = 2Then fx = fx + 1' Parse the year, using information from the string length variable.
endyr = Right(endate, Len(endate) - (sfunc("/", endate) + 1) - endvar + fx)
' Change the text values we obtained to integers for calculation ' purposes.
endmonf = CInt(endmon)
enddayf = CInt(endday)
endyrf = CInt(endyr)
' Check for valid date entries.If endmonf < 1Or endmonf > 12Or enddayf < 1Or enddayf > 31Or endyrf < 1Then
AgeFunc = "Invalid Date"ExitFunctionEndIf' Determine the initial number of years by subtracting the first and ' second year.
years = endyrf - styrf
' Look at the month and day values to make sure a full year has passed. If stmonf > endmonf Then
years = years - 1EndIfIf stmonf = endmonf And stdayf > enddayf Then
years = years - 1EndIf' Make sure that we are not returning a negative number and, if not, ' return the years.If years < 0Then
AgeFunc = "Invalid Date"Else
AgeFunc = years
EndIfEndFunction' This is a second function that the first will call.' It runs the Search worksheet function with arguments passed from AgeFunc.' It is used so that the code is easier to read.PublicFunction sfunc(x As Variant, y As Variant, Optional z As Variant)
sfunc = Application.WorksheetFunction.Search(x, y, z)
EndFunction
Guarde el archivo.
Escriba los datos siguientes:
asciidoc
A1 01/01/1887 A2 02/02/1945
En la celda A3, escriba la fórmula siguiente:
excel
=AgeFunc(startdate,enddate)
Startdate es una referencia de celda a la primera fecha (A1) y enddate es una referencia de celda a la segunda fecha (A2).
El resultado debe ser 58.
Nota
Compruebe si todas las fechas anteriores al 1/1/1900 son válidas. Excel no comprueba las fechas especificadas como texto.
Obtenga una certificación de Microsoft Office Specialist (MOS) para demostrar que tiene las habilidades necesarias para sacar el máximo partido de Excel 2016.
Proporciona la descripción de las diferencias entre el sistema de fechas 1900 y el sistema de fechas 1904 en Excel. Describe los problemas que puede experimentar al usar estos dos sistemas de fechas diferentes en libros de Excel.