将当前季度的第一个/最后一个日期简化为变量

时间:2014-05-15 18:47:27

标签: vba excel-vba excel

我觉得这应该可以用更少的线条来实现。我是否缺少VBA功能以使其更容易?

Sub dates()
Dim sDay As String
Dim eday As String
Quarter = DatePart(q, Date)
If Quarter = 1 Then
    sDay = "1/1/" & DatePart("yyyy", Date)
    eday = "3/31/" & DatePart("yyyy", Date)
ElseIf Quarter = 2 Then
    sDay = "4/1/" & DatePart("yyyy", Date)
    eday = "6/30/" & DatePart("yyyy", Date)
ElseIf Quarter = 3 Then
    sDay = "7/1/" & DatePart("yyyy", Date)
    eday = "9/30/" & DatePart("yyyy", Date)
ElseIf Quarter = 4 Then
    sDay = "10/1/" & DatePart("yyyy", Date)
    eday = "12/31/" & DatePart("yyyy", Date)
End If
End Sub

1 个答案:

答案 0 :(得分:1)

是的:

Sub dates()
Dim sDay As String
Dim eDay As String
Dim Quarter As Integer

For Quarter = 1 To 4

    sDay = CStr(3 * (Quarter - 1) + 1) & "/1/" & DatePart("yyyy", Date)
    eDay = DateAdd("d", -1, DateAdd("q", 1, CDate(sDay)))

    Debug.Print "Quarter : " & Quarter & vbTab & sDay & vbTab & eDay
Next

End Sub

另请注意,在您的代码中,q需要在双引号中作为字符串文字进行偏移,除非在其他地方定义为。

Quarter = DatePart("q", Date)