计算日期范围 cover/occur 中的一年中有多少周

counting how many weeks of the year date ranges cover/occur in

我在 sheet 中有许多记录,每条记录都有开始和结束日期。 每行都有一个记录号,有些行的记录号与其他行相同(sheet 列出案例和案例使用的日期。有些案例只有 1 行,而其他案例会有几行)

每个案例的日期不会重叠,但每个范围之间可能会有差距

例如:

案例# -- 开始日期 -- 结束日期
案例 1 - 01/01/2018 - 05/01/2018
案例 1 - 06/01/2018 - 13/01/2018
案例 1 - 17/03/2018 - 20/03/2018
案例 2 - 14/02/2018 - 15/02/2018
案例 3 - 19/05/2018 - 25/05/2018
案例 3 - 26/05/2018 - 28/05/2018

我需要知道这些日期范围涵盖了多少周。所以对于案例 1,它将是 4 周(第二行的开始日期仍然与第一行在同一周内,因此无需计算周数两次,第三行实际上发生在 2 个不同的周内,所以将被计算为 2 周)

我可以获得日期的周数(使用 ISOWEEKNUM),但我需要一个公式来查看该案例的所有行#,并且不包括间隔中的周数。如果我对案例 1 使用最早日期,然后使用最晚日期,则周数将为 12...

如果有人能提供帮助,我将不胜感激,我在搜索中找不到任何东西

TIA 干杯,纳特

编写一个用户定义的函数并在 sheet 中使用它?下面的 UDF 有四个参数:

arg1 Range caseNumber:这是包含要获取周数的案例编号的范围。必须是单个单元格。

arg2 Range rng: 这是不包括headers的数据范围。

arg3 Long startDateColumn:所选范围内包含开始日期的列号。不是 sheet.

中的列号

arg4 Long endDateColumn:包含结束日期的选定范围内的列号。不是 sheet.

中的列号

代码进入 VBE 项目的标准模块。


Public Function GetWeekCount(ByVal caseNumber As Range, ByVal rng As Range, ByVal startDateColumn As Long, ByVal endDateColumn As Long) As Variant
    Dim arr(), i As Long, j As Long, dict As Object
    If caseNumber.Count <> 1 Then GetWeekCount = CVErr(xlErrValue)
    Set dict = CreateObject("Scripting.Dictionary")
    arr = rng.Value
    For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i, 1) = caseNumber Then
            For j = CLng(DateValue(arr(i, startDateColumn))) To CLng(DateValue(arr(i, endDateColumn)))
                dict(Application.WorksheetFunction.IsoWeekNum(j)) = 1
            Next j
        End If
    Next i
    If dict.Count > 0 Then
        GetWeekCount = Application.WorksheetFunction.Sum(dict.items)
    Else
        GetWeekCount = 0
    End If
End Function

用法示例:


标准模块(不是 class 并且不在 sheet 窗格中):