stocksynd
stocksynd

Reputation: 29

Visual Basic: Calculating days until birthday from today

I need to make a function what calculates days until birthday from todays date. What I have so far is:

Function synnipaev(sk As Date, tana As Date)

synnipaev = DateDiff("d", sk, tana)

End Function

sk is birthdate in the Excel sheet (formated as 10.10.2001 DD/MM/YYYY)

tana is todays date in the Excel sheet ( =TODAY() DD/MM/YYYY)

It gives me the days but also includes the years. How to make the function not include years?

Upvotes: 1

Views: 2269

Answers (1)

Comintern
Comintern

Reputation: 22195

DateDiff is simply giving you the total number of days between the two dates. You need to find the difference between the current date and the next birthdate:

Public Function DaysToBirthday(birthday As Date) As Integer

    Dim targetYear As Integer

    'Has the birthday already passed this year?
    If Month(Now) > Month(birthday) Or _
       (Month(Now) = Month(birthday) And Day(Now) > Day(birthday)) Then
        'Then use next year.
        targetYear = Year(Now) + 1
    Else
        targetYear = Year(Now)
    End If

    DaysToBirthday = CInt(DateSerial(targetYear, Month(birthday), Day(birthday)) - Now)

End Function

Note: VBA stores Date variables as Doubles, with days to the left of the decimal and time to the right. If all you care about are days, you can save the function call and do a simple subtraction.

Upvotes: 2

Related Questions