从日历日期读取正确的周数

Read the correct week number from a calendar date

如您所见,我在 Excel 列中有以下日期。

Sprint 1 从 10.0421.04,这意味着 2 周,在括号中,它们被指定为第 15 周和第 16 周,这是正确的,但对于 Sprint 2,他们也在 10.04 开始] 但要等到 05.05 这意味着 7 周,但也会显示 Sprint1 的周数。

"Sprint1 (CW15-16/2017)
[10.04.2017 - 21.04.2017]
Sprint2 (CW15-16/2017)
[10.04.2017 - 05.05.2017]"

到目前为止我得到的是:

'reading the first CW of the sprint based on the date
SprintFristCW = Left(planning_wb.Worksheets(SprintPlanningTable).Cells(2, i + 1).Value, 9)

'reading the last CW of the Sprint based on the date
SprintEndCW = Right(planning_wb.Worksheets(SprintPlanningTable).Cells(2, i + Sprintlength).Value, 9)

SprintCW = Left(SprintFirstCW, 4) & "-" & Right(SprintEndCW, 7)

但是 SprintEndCW 读取的周数不正确。

所以我需要读取每个 sprint 结束的正确周数并打印出来。

不要创建庞大的程序。小就是美。创建提供给 Main 过程的函数。这是一个例子。过程 TestExtraction 调用函数 ExtractWeeks。因此 ExtractWeeks 不需要成为调用它的过程的一部分,从而使代码更易于理解和维护。

Private Sub TestExtraction()

    Dim Fun As Long
    Dim DateString As String
    Dim StartDate As Date, EndDate As Date

    DateString = ActiveCell.Value

    ' the DateString is re-defined here for testing purposes
    DateString = "[10.04.2017 - 05.05.2017]"


    Fun = ExtractWeeks(DateString, StartDate, EndDate)
    If Fun < 0 Then
        Debug.Print "Invalid date"
    Else
        With Application
            DateString = "(CW" & .WeekNum(StartDate)
            If Year(StartDate) <> Year(EndDate) Then _
                DateString = DateString & "/" & Year(StartDate)
            DateString = DateString & " - " & .WeekNum(EndDate) & "/" & Year(EndDate) & ")"
        End With
        Debug.Print DateString
        Debug.Print Fun & " weeks"
    End If
End Sub

Private Function ExtractWeeks(ByVal DateString As String, _
                              StartDate As Date, _
                              EndDate As Date) As Long
    ' 24 Oct 2017
    ' return the number of weeks between dates (rounded up)
    ' return -1 if one of the dates is unreadable

    Dim Dates() As String
    Dim i As Integer

    Dates = Split(Mid(DateString, 2, Len(DateString) - 2), "-")
    On Error Resume Next
    For i = 0 To 1
        Dates(i) = Replace(Trim(Dates(i)), ".", Application.International(xlDateSeparator))
    Next i
    StartDate = DateValue(Dates(0))
    EndDate = DateValue(Dates(1))
    If Err Then
        ExtractWeeks = -1
    Else
        ExtractWeeks = Int((StartDate - EndDate) / 7) * -1
    End If
End Function

重点是不是所有看起来像日期的都是日期Excel可以理解。函数 ExtractWeeks 在出错的情况下转换 "dates' from your worksheet into real dates and returns these dates to the calling procedure. It also returns -1 in case of error which you can use to trap such errors. In my example, the function returns the number of weeks (or -1). You might let it return the CW string my calling procedure constructs. You will find it easy to move the process of constructing that string to the function and let the function return "" 而不是 -1。也许你可以排除日期错误的可能性。这是一个问题,你如何将函数集成到你的 Main.