Dica do SistemaEste artigo aplica-se a um sistema operativo diferente do que está a utilizar. Foi desactivado o conteúdo do artigo, que pode não ser relevante para si.
Embora fórmulas do Microsoft Excel data só podem usar as datas inseridas entre 1/1/1900 e 31/12/9999, você pode usar um personalizado do Microsoft Visual Basic for aplicativos função para calcular a idade (em anos) de alguém ou algo que primeiro foi criada antes de 1 º de janeiro de 1900.
Microsoft fornece exemplos de programação apenas para ilustração, sem garantia expressa ou implícita. Isso inclui, mas não está limitado a, garantias implícitas de comercialização ou adequação para uma finalidade específica. Este artigo presume que você está familiarizados com a linguagem de programação que está sendo demonstrada e com as ferramentas que são usadas para criar e depurar procedimentos. Engenheiros de suporte podem ajudar a explicar a funcionalidade de um determinado procedimento, mas eles não modificarão esses exemplos para fornecer funcionalidades adicionais ou construir procedimentos para atender às suas necessidades. Excel insere datas anteriores a 1/1/1900 como texto. Essa função funciona para datas inseridas como texto que começa com 1/1/0001, datas normais e pode manipular datas quando a data inicial é antes de 1900 e data de término é posterior 1900. Para usar a macro, execute essas etapas:
Inicie o Excel. Exiba a planilha em que você deseja usar a função.
Pressione ALT + F11 para alternar para o Editor do Visual Basic.
No menu Inserir , clique em módulo .
Digite o seguinte código no 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
Salve o arquivo.
Digite os seguintes dados:
A1 01/01/1887
A2 02/02/1945
Na célula A3, digite a seguinte fórmula
= AgeFunc(startdate,enddate)
onde startdate é uma referência de célula para a primeira data (A1) e enddate é uma referência de célula para a segunda data (A2).
O resultado deve ser 58.
Observação : verificar todas as datas antes de 1/1/1900 para validade. Datas inseridas como texto não são verificados pelo Excel.
Para obter mais informações sobre como usar o código de exemplo neste artigo, clique no número abaixo para ler o artigo na Base de dados de Conhecimento da Microsoft:
212536
(http://support.microsoft.com/kb/212536/EN-US/
)
Como executar o código de exemplo de artigos da Knowledge Base
IMPORTANTE: Este artigo foi traduzido por um sistema de tradução automática (também designado por Machine Translation ou MT), não tendo sido portanto traduzido ou revisto por pessoas. A Microsoft possui artigos traduzidos por aplicações (MT) e artigos traduzidos por tradutores profissionais, com o objetivo de oferecer em português a totalidade dos artigos existentes na base de dados de suporte. No entanto, a tradução automática não é sempre perfeita, podendo conter erros de vocabulário, sintaxe ou gramática. A Microsoft não é responsável por incoerências, erros ou prejuízos ocorridos em decorrência da utilização dos artigos MT por parte dos nossos clientes. A Microsoft realiza atualizações freqüentes ao software de tradução automática (MT). Obrigado.
Clique aqui para ver a versão em Inglês deste artigo: 245104
(http://support.microsoft.com/kb/245104/en-us/
)
Quanto esforço foi necessário para seguir os procedimentos deste artigo?
Muito baixo
Baixo
Moderado
Alto
Muito alto
Diga-nos o porque e o que podemos fazer para melhorar esta informação
Obrigado! Seus comentários são usados para nos ajudar a aperfeiçoar o conteúdo de suporte. Para obter mais opções de ajuda, visite a Home Page de Ajuda e Suporte.