excel 如何根据季度末计算开始日期和结束日期

hfyxw5xn  于 2022-11-18  发布在  其他
关注(0)|答案(3)|浏览(155)

我需要自动计算起始日期(aka QRT_START),它是5年前的季度。一个季度是3个月。例如,一年中有4个季度:3月31日、6月30日、9月30日和12月31日。


由于我们目前处于2022年11月16日,因此开始日期应为2017年12月31日。因此,根据当前日期,开始日期需要回溯5年的季度。
我还需要自动计算最近的结束日期(也称为QRT_END)。因此,由于我们是在2022年11月16日,结束日期将是今天之前的上一个季度结束日期,即2022年9月30日。我有下面写的VBA代码,请帮助我修复。

Private Function getQRT_END() As String

    Dim endmonth As Variant
    Dim endyear As Variant
    Dim Day As Variant

    endmonth = Month(Date) - 1
    If endmonth = 0 Then
        endyear = Year(Date) - 1
        endmonth = 12
        day = 31
    Else
        endyear = Year(Date)
        If endmonth = 3 Then
            day = 31
        Else
            day = 30
        End if
        endmonth = “0” & endmonth
    End If
    getQRT_END = endyear & endmonth & day
End Function

Private Function getQRT_START() As String
    Dim startmonth As Variant
    Dim startyear As Variant
    Dim Day As Variant
    
    startyear = Year(Date) - 5
    startmonth = Month(Date) + 2
    If startmonth <10 Then
        If startmonth = 3 Then
        day = 31
    Else
        day = 30
        
    End if
    startmonth  = “0” & startmonth
    Else
        day = 30
    End If

    getQRT_START = startyear & startmonth & day
End Function
avwztpqn

avwztpqn1#

您可以使用我在GitHub的库中找到的两个函数:VBA.Date

? DateThisQuarterUltimo(DateAdd("yyyy", -5, Date))
2017-12-31 

? DatePreviousQuarterUltimo(DateAdd("yyyy", -5, Date))
2017-09-30

它们是简单的高级函数:
第一次

ljsrvy3e

ljsrvy3e2#

还没有完全测试过
你可以使用DateSerialDateAddDatePart来实现你想要的...

Option Explicit

Sub Sample()
    Dim D As Date
    Dim prevD As Date
    
    D = DateSerial(2022, 11, 16)
    
    '~~> Date 5 years years ago
    prevD = DateAdd("q", -(4 * 5), D)
    
    '~~> Last date of the quarter for a specific date
    Debug.Print DateAdd("q", DatePart("q", prevD), DateSerial(Year(prevD), 1, 1)) - 1
    'OUTPUT : 31-12-2017
    
    '~~> Last date of previous quarter for a specific date
    Debug.Print DateAdd("q", DatePart("q", D) - 1, DateSerial(Year(D), 1, 1)) - 1
    'OUTPUT : 30-09-2022
End Sub

将字符串部分更改为正确的日期。

相关问题