vba 获取一年中的第一天和最后一天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43030431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get First And Last Day Of Year
提问by IcyPopTarts
In VBA I know you can use this syntax to subtract a year from a date
在 VBA 中,我知道您可以使用此语法从日期中减去一年
Dim testdate As String, DateTest As String
testdate= "03/21/2017"
DateTest = Month(testdate) & "/" & Day(testdate) & "/" & Year(testdate) - 1
But how could you find the first and last date of a given year? For example, let's use the same date
但是你怎么能找到给定年份的第一个和最后一个日期呢?例如,让我们使用相同的日期
testdate = "03/21/2017"
and get the following values
并获得以下值
firstdate = "01/01/2017"
lastdate = "12/31/2017"
采纳答案by WNG
If it is always the beginning and the end of the year that interest you, you can just use the 1st of January and the 31st of december. To mimic your syntax :
如果您始终对年初和年末感兴趣,则可以仅使用 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)
回答by Fadi
You can use DateSerial
:
您可以使用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