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


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

Sprint 1从10.0421.04,这意味着2周,在括号之间指定了第15周和第16周,这是正确的,但对于同样从10.04开始但一直持续到05.05的Sprint 2来说,它意味着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没有正确读取周数。

所以我需要阅读每个冲刺结束的正确周数并打印出来

不要创建庞大的过程。小即美丽。创建供Main过程使用的函数。下面是一个例子。过程CCD_ 7调用函数CCD_。因此,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中的问题。

最新更新