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

时间:2017-10-24 08:44:36

标签: excel vba excel-vba date week-number

我在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结束并打印出来。

1 个答案:

答案 0 :(得分:4)

不要创建庞大的程序。小是美丽的。创建提供给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将工作表中的“日期”转换为实际日期,并将这些日期返回给调用过程。如果出现错误,它还会返回-1,您可以使用它来捕获此类错误。在我的示例中,函数返回周数(或-1)。你可以让它返回我的调用程序构造的CW字符串。你会发现很容易将构造该字符串的过程移动到函数中并让函数返回“”以防万一错误而不是-1。也许您可以排除日期中出错的可能性。这是您如何将该功能集成到Main中的问题。