提问人:Dhruva 提问时间:11/3/2023 最后编辑:Dhruva 更新时间:11/3/2023 访问量:51
查找日期范围内一个季度中的天数
Find days in a quarter in a date range
问:
我的工作表如下所示
我能够获得单元格 D4 中所示的日期范围之间的总季度数。我创建了一个 UDF,它运行良好。
Function GetDayPerQtr(ReimDt As Date, HoldDt As Date) As String
Dim Qtr As Integer
Dim QtrStDt As Date
Dim QtrEndDate As Date
Dim TotalQtrs As Long
Dim tmp As String
Dim i As Long
Qtr = DetermineQuarter(ReimDt)
QtrEndDate = DateSerial(Year(ReimDt), (Qtr * 3) + 1, 0)
If QtrEndDate <= HoldDt Then
TotalQtrs = DateDiff("q", ReimDt, HoldDt)
If TotalQtrs > 1 Then
QtrStDt = ReimDt
For i = 1 To TotalQtrs
Qtr = DetermineQuarter(QtrStDt)
If Qtr = 2 Or Qtr = 3 Then
QtrEndDate = DateSerial(Year(QtrStDt), Qtr * 3, 30)
Else
QtrEndDate = DateSerial(Year(QtrStDt), Qtr * 3, 31)
End If
tmp = tmp & ", " & (QtrEndDate - QtrStDt + 1)
QtrStDt = QtrEndDate + 1
Next i
tmp = tmp & ", " & (HoldDt - QtrStDt + 1)
tmp = Mid(tmp, 2)
Else
tmp = QtrEndDate - ReimDt
QtrStDt = QtrEndDate + 1
tmp = tmp & ", " & (HoldDt - QtrStDt + 1)
End If
Else
tmp = HoldDt - ReimDt
End If
GetDayPerQtr = tmp
End Function
Function DetermineQuarter(Dt As Date) As Integer
Dim inputDate As Date
Dim quarter As Integer
Dim inputMonth As Integer
inputDate = Dt
inputMonth = Month(inputDate)
If inputMonth >= 1 And inputMonth <= 3 Then
quarter = 1
ElseIf inputMonth >= 4 And inputMonth <= 6 Then
quarter = 2
ElseIf inputMonth >= 7 And inputMonth <= 9 Then
quarter = 3
ElseIf inputMonth >= 10 And inputMonth <= 12 Then
quarter = 4
End If
DetermineQuarter = quarter
End Function
现在,我正在尝试根据开始日期和结束日期获得绿色单元格中显示的结果。
所以基本上,我在单元格 D4 中显示的值应该进入相应的列。
我尝试了上述代码的各种组合,最终感到困惑。有人可以帮助我或指导我如何实现我想要的吗?我对 VBA 和 Excel 公式的建议持开放态度。
我还试图在下面加入一个逻辑,但被卡住了。
'=GetTotalDaysInQtr("Q1",2020,B4,C4)
Function GetTotalDaysInQtr(Qtr As String, Yr As Long, ReimDt As Date, HoldDt As Date) As Long
End Function
答:
评论