Excel VBA:日期比较

时间:2017-07-18 13:42:06

标签: excel vba excel-vba date excel-2010

所以我目前正在尝试制作一个代码,将当前日期与其他两个日期进行比较,以确定信息的有效性。例如,如果日期介于一年的第一季度和第二季度之间,则该文档的信息截至第一季度日期(3月31日)。以下是我目前所拥有的,由于某些原因,即使当前日期是在7月,代码仍然说该信息在3月31日有效。任何人都有任何建议吗?

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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