[英]Excel VBA: Date Comparison
因此,我目前正在嘗試編寫代碼以將當前日期與其他兩個日期進行比較,以確定信息的有效性。 例如,如果日期在一年的第一季度和第二季度之間,則該文檔上的信息以第一季度的日期(3月31日)為准。 以下是我目前擁有的內容,由於某種原因,即使當前日期為七月,代碼仍會說該信息自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
如果您嘗試將日期格式設置為季度,則不需要所有的結束日期和比較,可以在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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.