在 VBA 中,我知道您可以使用此语法从日期中减去一年
Dim testdate As String, DateTest As String
testdate= "03/21/2017"
DateTest = Month(testdate) & "/" & Day(testdate) & "/" & Year(testdate) - 1
但是,您如何找到给定年份的第一天和最后一个日期呢? 例如,让我们使用相同的日期
testdate = "03/21/2017"
并获取以下值
firstdate = "01/01/2017"
lastdate = "12/31/2017"
您可以使用
DateSerial
:
Sub Test()
Dim dt As Date, firstDay As Date, lastDay As Date
dt = Date
firstDay = DateSerial(Year(dt), 1, 1)
lastDay = DateSerial(Year(dt), 12, 31)
Debug.Print firstDay
Debug.Print lastDay
End Sub
如果您总是对一年的开始和结束感兴趣,您可以使用 1 月 1 日和 12 月 31 日。要模仿您的语法:
Dim testdate As String, DateTest As String
testdate= "03/21/2017"
FirstDayOfYear = "1/1/" & Year(testdate)
LastDayOfYear = "12/31/" & Year(testdate)