从日历date读取正确的星期编号

如下所示,我在Excel列中具有以下date。

冲刺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结束并打印的正确周编号。

不要创build大量的程序。 小是美丽的。 创build提供给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 

问题是,并非所有看起来像date的东西都是Excel可以理解的date。 函数ExtractWeeks将工作表中的“date”转换为实际date,并将这些date返回给调用过程,如果发生错误,它也会返回-1,用于捕获这样的错误。在我的例子中,函数返回数字你可能会让它返回我的调用过程结构中的CWstring,你会发现把这个string的构造过程移动到函数中是很容易的,并且让函数在发生错误时返回“”,而不是-1。也许你可以排除date错误的可能性,这是一个如何将函数集成到Main