【问题标题】:Visual Basic: Calculating days until birthday from todayVisual Basic:计算从今天到生日的天数
【发布时间】:2015-04-10 00:24:54
【问题描述】:

我需要创建一个函数来计算从今天到生日的天数。 到目前为止我所拥有的是:

Function synnipaev(sk As Date, tana As Date)

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

End Function

sk 是 Excel 表中的生日(格式为 10.10.2001 DD/MM/YYYY)

tana 是 Excel 工作表中的今天日期 (=TODAY() DD/MM/YYYY)

它给了我日子,但也包括了岁月。 如何使函数不包含年份?

【问题讨论】:

  • 你的意思是它还包括年份?
  • 例如生日 = 10.10.2001 和今天 = 10.04.2015。答案应该是 183,但实际上是 4930
  • 为什么答案是 183? 10 月 4 日和 10 月 10 日之间相差 6 天。这没有任何意义。您需要多解释一下您的期望以及它应该如何工作。
  • @stocksynd 使用10.10.2001 是个坏主意,因为不清楚哪个是月份,哪个是日期。
  • 现在应该更容易理解了

标签: vba date


【解决方案1】:

DateDiff 只是为您提供两个日期之间的总天数。您需要找出当前日期与下一个生日之间的差异:

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

注意:VBA 将 Date 变量存储为 Doubles,小数点左侧为天,右侧为时间。如果你只关心天数,你可以保存函数调用并做一个简单的减法。

【讨论】:

  • 看起来很棒!谢谢!但如果生日日期大于今天的值,它会给出负值。例如生日 = 30.01.2001 和今天 = 10.04.2015 给出 -70
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2020-12-01
  • 1970-01-01
  • 2012-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多