2017-07-18 215 views
1

所以我目前正在尝试做一个代码来比较当前日期和其他两个日期以确定信息的有效性。例如,如果日期在一年的第一季度和第二季度之间,则该文件的信息是截至第一季度日期(3月31日)。以下是我目前拥有的信息,由于某些原因,即使当前日期是七月份,代码仍然会说这些信息在三月三十一日有效。任何人有任何建议吗?Excel VBA:日期比较

crntDate = Date 
q1End = CDate("Mar 31" & " " & Year(Date)) 
q2End = CDate("Jun 30" & " " & Year(Date)) 
q3End = CDate("Sep 30" & " " & Year(Date)) 
q4End = CDate("Dec 31" & " " & Year(Date)) 

If q1End <= crntDate <= q2End Then 
    quart = "Q1" & " " & Year(Date) 
ElseIf q2End <= crntDate <= q3End Then 
    quart = "Q2" & " " & Year(Date) 
ElseIf q3End <= crntDate <= q4End Then 
    quart = "Q3" & " " & Year(Date) 
Else 
    quart = "Q4" & " " & Year(Date) 
End If 

shName = "Quarterly Reporting for" & " " & firstName & " " & lastName & " " & "(" & quart & ")" 
With wdApp.ActiveDocument 
    .SaveAs2 "https://path/" & shName & ".docx" 
    .Close 
End With 

回答

3

如果你想对日期进行格式为宿舍,你并不需要所有的结束日期和比较,你可以在VBA中使用整数除法\

Sub test() 

    Dim quart As String 
    quart = GetDateAsQuarterYear(VBA.Date) 

    shName = "Quarterly Reporting for" & " " & firstName & " " & lastName & " " & "(" & quart & ")" 
    With wdApp.ActiveDocument 
    .SaveAs2 "https://path/" & shName & ".docx" 
    .Close 
    End With 
End Sub 

Function GetDateAsQuarterYear(crntDate As Date) As String 

    Dim quarterEnd As Date 
    quarterEnd = DateSerial(Year(crntDate), 1 + 3 * (1 + (Month(crntDate) - 1) \ 3), 0) 

    GetDateAsQuarterYear = "Q" & 1 + (Month(crntDate) - 1) \ 3 & " (" & Format$(quarterEnd, "mmmm d, yyyy") & ")" 

End Function 
+0

如果我正在寻找实际的季度日期以显示功能,那么呢? (例如,3月31日,Q1,6月30日,Q2等等) –

+0

我已更新代码以修复非季度末月的错误,并将季度末日期添加为' Q3(2017年9月30日)' – ThunderFrame

2

q1End <= crntDate <= q2End在Excel中不能正常工作,它需要是:

q1End <= crntDate and crntDate <= q2End 

所以

crntDate = Date 
q1End = CDate("Mar 31" & " " & Year(Date)) 
q2End = CDate("Jun 30" & " " & Year(Date)) 
q3End = CDate("Sep 30" & " " & Year(Date)) 
q4End = CDate("Dec 31" & " " & Year(Date)) 

If q1End <= crntDate and crntDate <= q2End Then 
    quart = "Q2" & " " & Year(Date) 
ElseIf q2End <= crntDate and crntDate <= q3End Then 
    quart = "Q3" & " " & Year(Date) 
ElseIf q3End <= crntDate and crntDate <= q4End Then 
    quart = "Q4" & " " & Year(Date) 
Else 
    quart = "Q1" & " " & Year(Date) 
End If 

shName = "Quarterly Reporting for" & " " & firstName & " " & lastName & " " & "(" & quart & ")" 
With wdApp.ActiveDocument 
    .SaveAs2 "https://path/" & shName & ".docx" 
    .Close 
End With 
+0

该死的,正要张贴:) –

+0

还在想就像我在Python编程 - 多谢@ScottCraner :) –

+2

IIUC ,, CDATE将是受制于区域/语言设置用户,所以如果你在VBA中声明日期,你最好使用'DateSerial(year,month,day)'或本地语法'#mm/dd/yyyy#'。 – ThunderFrame