我试图创建一些 VB 代码来获取上个月的开始和结束。我能够到当前月份,这只是:
Month(DateValue(Now))
这将返回 3。从那里我可以带走 1 给我 2 意思是二月。这很好,但是当我在一月份我重复这个并且它给我零时 - 我的代码将失败。有谁知道如何获得前几个月的开始和结束日期?
谢谢
上个月的第一天始终为 1,要获取上个月的最后一天,请将 0 与 DateSerial 一起使用:
''Today is 20/03/2013 in dd/mm/yyyy
DateSerial(Year(Date),Month(Date),0) = 28/02/2013
DateSerial(Year(Date),1,0) = 31/12/2012
你可以像这样从上面得到第一天:
LastDay = DateSerial(Year(Date),Month(Date),0)
FirstDay = LastDay-Day(LastDay)+1
第一天和最后一天我有类似的公式
每月第一天
FirstDay = DateSerial(Year(Date),Month(Date),1)
下个月的零日是该月的最后一天
LastDay = DateSerial(Year(Date),Month(Date)+ 1,0)
firstDay = DateSerial(Year(DateAdd("m", -1, Now)), Month(DateAdd("m", -1, Now)), 1)
lastDay = DateAdd("d", -1, DateSerial(Year(Now), Month(Now), 1))
这是另一种方法,但我认为 Remou 的版本看起来更干净。
试试这个
First_Day_Of_Previous_Month = New Date(Today.Year, Today.Month, 1).AddMonths(-1)
Last_Day_Of_Previous_Month = New Date(Today.Year, Today.Month, 1).AddDays(-1)
这在我的主子中对我来说很可靠。
Dim defDate1 As Date, defDate2 As Date
'** Set default date range to previous month
defDate1 = CDate(Month(Now) & "/1/" & Year(Now))
defDate1 = DateAdd("m", -1, defDate1)
defDate2 = DateAdd("d", -1, DateAdd("m", 1, defDate1))
试试这个以数字形式获取月份:
Month(DateAdd("m", -3, Now))
它会给你12
十二月的。
因此,在您的情况下,您将Month(DateAdd("m", -1, Now))
过去只减去一个月。
只是在@Fionnuala 所说的内容中添加一些内容,可以使用以下功能。这些甚至适用于闰年。
'If you pass #2016/20/01# you get #2016/31/01#
Public Function GetLastDate(tempDate As Date) As Date
GetLastDate = DateSerial(Year(tempDate), Month(tempDate) + 1, 0)
End Function
'If you pass #2016/20/01# you get 31
Public Function GetLastDay(tempDate As Date) As Integer
GetLastDay = Day(DateSerial(Year(tempDate), Month(tempDate) + 1, 0))
End Function
Public Shared Function GetFOMPrev(ByVal tdate As Date) As Date
Return tdate.AddDays(-(tdate.Day - 1))
End Function
Public Shared Function GetEOMPrev(ByVal tdate As Date) As Date
Return tdate.AddDays(-tdate.Day)
End Function
用法:
'Get End of Month of Previous Month - Pass today's date
EOM = GetEOMPrev(Date.Today)
'Get First of Month of Previous Month - Pass date just calculated
FOM = GetFOMPrev(EOM)