Aunque las fórmulas de fecha de Microsoft Excel sólo pueden utilizar las fechas escritas entre 1, 1/1900 y 31/12/9999, puede utilizar un personalizado de Microsoft Visual Basic para aplicaciones función para calcular la antigüedad (en años) de alguien o algo que se creó primero antes 1 de del de enero de 1900.
Microsoft proporciona ejemplos de programación con fines ilustrativos únicamente, sin ninguna garantía tanto expresa como implícita. Esto incluye, entre otras, las garantías implícitas de comerciabilidad e idoneidad para un fin determinado. Este artículo se supone que está familiarizado con el lenguaje de programación que se muestra y con las herramientas que se utilizan 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 que cumplan sus requisitos específicos. Excel introduce las fechas anteriores al 1, 1/1900 como texto. Esta función funciona para las fechas introducidas como texto que comienza con 1, 1/0001, fechas normales y puede controlar fechas cuando la fecha inicial es anterior a 1900 y fecha final es posterior a 1900. Para utilizar la macro, siga estos pasos:
Inicie Excel. Ver la hoja de cálculo en el que desea utilizar la función.
Presione ALT+F11 para cambiar el Editor de Visual Basic.
En el menú Insertar , haga clic en módulo .
Escriba el código siguiente en el módulo:
' This is the initial function. It takes in a start date and an end date.
Public Function AgeFunc(stdate As Variant, endate As Variant)
' Dim our variables.
Dim stvar As String
Dim stmon As String
Dim stday As String
Dim styr As String
Dim endvar As String
Dim endmon As String
Dim endday As String
Dim endyr As String
Dim stmonf As Integer
Dim stdayf As Integer
Dim styrf As Integer
Dim endmonf As Integer
Dim enddayf As Integer
Dim endyrf As Integer
Dim years As Integer
' This variable will be used to modify string length.
Dim fx As Integer
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) = 1 Then fx = fx + 1
If Len(stmon) = 2 Then 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 < 1 Or stmonf > 12 Or stdayf < 1 Or stdayf > 31 Or styrf < 1 Then
AgeFunc = "Invalid Date"
Exit Function
End If
' 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) = 1 Then fx = fx + 1
If Len(endmon) = 2 Then 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 < 1 Or endmonf > 12 Or enddayf < 1 Or enddayf > 31 Or endyrf < 1 Then
AgeFunc = "Invalid Date"
Exit Function
End If
' 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 - 1
End If
If stmonf = endmonf And stdayf > enddayf Then
years = years - 1
End If
' Make sure that we are not returning a negative number and, if not,
' return the years.
If years < 0 Then
AgeFunc = "Invalid Date"
Else
AgeFunc = years
End If
End Function
' 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.
Public Function sfunc(x As Variant, y As Variant, Optional z As Variant)
sfunc = Application.WorksheetFunction.Search(x, y, z)
End Function
Guarde el archivo.
Escriba los datos siguientes:
A1 01/01/1887
A2 02/02/1945
En la celda A3, escriba la fórmula siguiente
= AgeFunc(startdate,enddate)
donde startdate es una referencia de celda en la primera fecha (A1) y enddate es una referencia de celda a la segunda fecha (A2).
El resultado debería ser 58.
Nota : proteger todas las fechas de validez antes de 1, 1/1900. Fechas introducidas como texto no se comprueban por Excel.
Para obtener información adicional acerca de cómo utilizar el código de ejemplo de este artículo, haga clic en el número de artículo siguiente para verlo en Microsoft Knowledge Base:
212536
(http://support.microsoft.com/kb/212536/EN-US/
)
Cómo ejecutar código de ejemplo de artículos de Knowledge Base
IMPORTANTE: Este artículo ha sido traducido por un software de traducción automática de Microsoft (http://support.microsoft.com/gp/mtdetails) en lugar de un traductor humano. Microsoft le ofrece artículos traducidos por un traductor humano y artículos traducidos automáticamente para que tenga acceso en su propio idioma a todos los artículos de nuestra base de conocimientos (Knowledge Base). Sin embargo, los artículos traducidos automáticamente pueden contener errores en el vocabulario, la sintaxis o la gramática, como los que un extranjero podría cometer al hablar el idioma. Microsoft no se hace responsable de cualquier imprecisión, error o daño ocasionado por una mala traducción del contenido o como consecuencia de su utilización por nuestros clientes. Microsoft suele actualizar el software de traducción frecuentemente.
Haga clic aquí para ver el artículo original (en inglés): 245104
(http://support.microsoft.com/kb/245104/en-us/
)
Proporcione sus comentarios acerca de esta información
¿Esta información le ayudó a resolver su problema?
Sí
No
No lo sé
¿La información era relevante?
Sí
No
¿Qué podemos hacer para mejorar esta información?
Para proteger su privacidad, no incluya información de contacto en los comentarios.
¡Muchas gracias! Sus comentarios nos ayudarán a mejorar los contenidos de soporte. Para más opciones de asistencia, visite la página de Ayuda y soporte técnico.