我找到了很多函数来确定特定日期是一年中的哪一天:
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
也许是这样的,
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date
getDateBasedOnYearAndDayOfYear = dateserial(year, 1, 0) + dayofyear
end function
只需创建一个新日期,将过去的一年的 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