使用用户定义的函数分配计算值

问题描述 投票:0回答:1
Function GRADE(ByVal cellref As Range) As Integer
     Dim gd As String
     Dim cr As Integer
     'MsgBox cellref
     'MsgBox VarType(cellref)
     cr = CInt(cellref.Value)
        If (cr >= 95) Then
            gd = "A++"
        ElseIf ((cr >= 90) And (cr <= 94)) Then
            gd = "A+"
        ElseIf ((cr >= 85) And (cr <= 89)) Then
            gd = "A"
        ElseIf ((cr >= 80) And (cr <= 84)) Then
            gd = "B++"
        ElseIf ((cr >= 75) And (cr <= 79)) Then
            gd = "B+"
        ElseIf ((cr >= 70) And (cr <= 74)) Then
            gd = "B"
        ElseIf ((cr >= 60) And (cr <= 69)) Then
            gd = "C"
        ElseIf ((cr >= 50) And (cr <= 59)) Then
            gd = "D"
        ElseIf ((cr >= 40) And (cr <= 49)) Then
            gd = "E"
        Else
            gd = "U"
        End If
    ActiveCell.Value2 = CDbl(gd)
End Function
excel vba reference cell
1个回答
0
投票

您提供的函数似乎是一个 VBA 函数,旨在根据学生的分数对其进行评分。但是,该功能存在一些问题:

  1. 该函数应该返回一个
    Integer
    ,但您试图为其分配一个
    String
    值 (
    gd
    )。
  2. 该函数正在尝试为
    ActiveCell
    赋值。对于函数来说这不是一个好的做法。函数应该返回值,而不是直接修改单元格。
  3. ActiveCell.Value2 = CDbl(gd)
    会抛出错误,因为您试图将字符串 (
    gd
    ) 转换为双精度型。

这是该函数的更正版本:

Function GRADE(ByVal cellref As Range) As String
    Dim cr As Integer
    cr = CInt(cellref.Value)
    
    If (cr >= 95) Then
        GRADE = "A++"
    ElseIf ((cr >= 90) And (cr <= 94)) Then
        GRADE = "A+"
    ElseIf ((cr >= 85) And (cr <= 89)) Then
        GRADE = "A"
    ElseIf ((cr >= 80) And (cr <= 84)) Then
        GRADE = "B++"
    ElseIf ((cr >= 75) And (cr <= 79)) Then
        GRADE = "B+"
    ElseIf ((cr >= 70) And (cr <= 74)) Then
        GRADE = "B"
    ElseIf ((cr >= 60) And (cr <= 69)) Then
        GRADE = "C"
    ElseIf ((cr >= 50) And (cr <= 59)) Then
        GRADE = "D"
    ElseIf ((cr >= 40) And (cr <= 49)) Then
        GRADE = "E"
    Else
        GRADE = "U"
    End If
End Function

通过此更正后的函数,您可以在 Excel 中使用它,如下所示:

=GRADE(A1)
,其中
A1
包含分数。该函数将以字符串形式返回成绩。

© www.soinside.com 2019 - 2024. All rights reserved.