0

我需要一个函数来确定学生是在第一年、第二年还是第三年学习,或者他们是否已经毕业,基于 a)他们正在学习的证书和 b)他们开始的日期。

这是我的第一次努力 - 任何反馈将不胜感激:

[编辑:问题是函数在 Excel 中使用时返回错误]

[EDIT2:将 DateDiff 部分中的 m 更改为“m”,从而消除了错误 - 现在的问题是二年级和三年级学生被标记为“过去”]

Function YearCalc(start, course)

    'Introduce length - the course length in years
    Dim length As Integer

    'Define length corresponding to specific courses

    If course = "Msc" Then
        length = 3
    ElseIf course = "Adv Dip" Then
        length = 2
    ElseIf course = "PG Cert" Then
        length = 1
    End If

    Dim lengthm As Integer

    lengthm = (length * 12)

    'Define diff as the month difference between two dates;
    'today's date and the date the course was started.

    diff = DateDiff("m", start, Date, vbMonday)

    'Compare the date difference to the length of the course,
    'such that if the difference is larger than length of the specific course
    'the student is marked as 'Past':

    If diff >= (lengthm) Then
        YearCalc = "Past"

    'If the difference is less than the length of the course, determine which
    'year they fall into:

    Else
        If 0 <= (diff - lengthm) < 1 Then
            YearCalc = 1
        ElseIf 1 <= (diff - lengthm) < 2 Then
            YearCalc = 2
        ElseIf 2 <= (diff - lengthm) < 3 Then
            YearCalc = 3
        End If
    End If

End Function
4

1 回答 1

0

我建议更改为Select Case,作为仅返回 1 值的部分原因是双重比较。
0 <= AnyComparison将始终评估为True

Select Case course 
    Case "Msc" 
        length = 36
    Case "Adv Dip" 
        length = 24
    Case "PG Cert" 
        length = 12
End Select

Select Case (diff - lengthm)
    Case <0
        YearCalc = "Past"
    Case 0 to 11
        YearCalc = 1
    Case 12 to 23
        YearCalc = 2
    Case 24 to 35
        YearCalc = 3
    Case Else 
        YearCalc = "Course too long?"
End Select
于 2012-06-25T15:59:30.320 回答