【问题标题】:How to calculate what date a particular day of the year is in excel?如何在excel中计算一年中特定日期的日期?
【发布时间】:2015-06-25 02:01:29
【问题描述】:

我发现了很多函数来确定特定日期是一年中的哪一天

Function Yearday(dat As Date) As Integer
    'Purpose: does the same as day for month
    'Use to access an array where the index corresponds to days

    Yearday = DateDiff("d", CDate("1/1/" & Year(dat)), dat) + 1
End Function

但我还没有找到任何函数来根据特定年份的某天确定日期。

函数签名如下所示:

Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date

【问题讨论】:

  • 公式 "=DATE(year,1,dayOfYear)" 会起作用,除非我没有正确理解这个问题。这是在单元格中,因此您需要将其转换为适当的 VBA 宏

标签: excel vba date ms-access-2007


【解决方案1】:

只需使用过去一年的一月创建一个新日期,然后添加天数。这在 VBA 中非常简单,因为日期只是双倍,整数部分表示自 1899 年 12 月 31 日以来的天数。

从这里开始:

Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) As Date

    Dim result As Date

    result = DateSerial(year, 1, 1)
    getDateBasedOnYearAndDayOfYear = result + dayOfYear - 1

End Function

我可能会添加边界检查等,即一年中的第 -634 天没有多大意义。

编辑:

刚刚针对 DateSerial 进行了测试 - 您甚至不需要做数学运算:

Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) As Date

    getDateBasedOnYearAndDayOfYear = DateSerial(year, 1, dayOfYear)

End Function

【讨论】:

    【解决方案2】:

    也许是这样的,

    Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date
        getDateBasedOnYearAndDayOfYear = dateserial(year, 1, 0) + dayofyear
    end function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-13
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多