Calculate age by date of birth

I'm trying to calculate the age in a field of a form through the date of birth, only it returns me the compile error 13 type mismatch. Can someone please help me? Here's the code.

Private Sub CmbCalcular_Click()

    Dim datanasc As Date, idade As Integer

    datanasc = CDate(MskDataNasc.Mask)
    idade = CInt((Date - datanasc) / 365)
    TxtIdade = Str(idade) & "anos"

End Sub
Author: novic, 2016-10-20

2 answers

There are some errors your example. In line idade = CInt((Date - datanasc) / 365) you are using Class Date as if it were an instance.

Another thing is that to get time intervals like number of days, months or number of years use the Class TimeSpan(https://docs.microsoft.com/system.timespan )

Private Sub CmbCalcular_Click()

    ' Declare a variável intervalo com sendo do tipo TimeSpan
    Dim datanasc As Date, idade As Integer, intervalo As TimeSpan

    'Use propriedade Text ao invés de Mask. 
    'Mask é mascara de edição e Text é o valor digitado  
    datanasc = CDate(MskDataNasc.Text)

    ' Compute a diferença ente hoje e datanasc 
    intervalo = Now - datanasc;

    ' use a propriedade TotalDays para obter número de dias decorridos
    idade = Math.Abs(intervalo.TotalDays  / 365)

    TxtIdade = Str(idade) & "anos"

End Sub
 1
Author: Augusto Vasques, 2019-01-27 13:03:53

Use IsDate(valor) which will return true if the date is valid, use Text to get the value of the content MaskedBox and finally not Date is Now to catch the current date, that is, you have three problems in your code:

solution:

Private Sub CmbCalcular_Click()    
    Dim datanasc As Date, idade As Integer
    If IsDate(MskDataNasc.Text) Then
          datanasc = CDate(MskDataNasc.Text)
          idade = CInt((Now - datanasc) / 365)
          TxtIdade = Str(idade) & "anos"
    Else
          TxtIdade.Text = "Data inválida" 
    End If    
End Sub

The error reported type mismatch , means you tried to convert to a certain type, but, this conversion is not valid, so use IsDate(valor) before to check if conversion to Date

 0
Author: novic, 2016-10-20 15:15:25