VBA 迭代不返回值

VBA iteration not returning value

我正在编写一个非常简单的子流程来将字母等级分配给数字等级值。我有一个循环,我正在尝试将单元格值设置为我的函数的输出。这似乎是一项非常简单的任务,但我循环的前两次迭代没有分配任何值。我的循环只经过 4 行。

Function get_letter(grade As Double)
    Select Case grade
        Case 0 To 59: letter = "F"
        Case 60 To 69: letter = "D"
        Case 70 To 79: letter = "C"
        Case 80 To 89: letter = "B"
        Case 90 To 100: letter = "A"
    End Select
    get_letter = letter
End Function

Sub assign_letter_grade()
    Dim x As Integer
    Dim grade As Range
    Dim letter As Range

    num_rows = Range("A2", Range("A2").End(xlDown)).Rows.Count

    Set grade = Range("J2")
    Set letter = Range("K2")

    For x = 1 To num_rows
        letter.Value = get_letter(grade.Value)
        Set grade = grade.Offset(1, 0)
        Set letter = letter.Offset(1, 0)
    Next
End Sub

为什么这不设置循环中前两行的值?

问题来自于不包含在范围内的分数。对于 VBA,79.25 的分数不属于案例 C 或案例 B。您可以尝试查看以下是否可以解决问题:

Function get_letter(grade As Double)
Select Case grade
    Case 0 To 59.99: letter = "F"
    Case 60 To 69.99: letter = "D"
    Case 70 To 79.99: letter = "C"
    Case 80 To 89.99: letter = "B"
    Case 90 To 100.99: letter = "A" ' assuming student can get a score over 100
End Select
get_letter = letter
End Function

试试这个:

Function get_letter(grade As Double) As String
    if grade < 60 Then
        get_letter = "F"
    Elseif grade < 70 Then
        get_letter = "D"
    Elseif grade < 80 Then
        get_letter = "C"
    Elseif grade < 90 Then
        get_letter = "B"
    Else
        get_letter = "A"
    End If
End Function

因为您从第 2 行开始:

Set grade = Range("J2")
Set letter = Range("K2")

然后在循环中立即偏移 1 行:

Set grade = grade.Offset(1, 0)
Set letter = letter.Offset(1, 0)

因此缺少第 1 到 2 行并从第 3 行开始。在循环中使用 x 变量来更正问题:

For x = 1 To num_rows
    letter.Value = get_letter(grade.Value)
    Set grade = Range("J" & x)
    Set letter = Range("K" & x)
Next

或使用INDEX/MATCH

Function get_letter(grade As Double) As String
get_letter = Evaluate("INDEX({""F"",""D"",""C"",""B"",""A""},MATCH(" & grade & ",{0,60,70,80,90,100}))")
End Function

样本

Sub b()
Debug.Print get_letter(59.99)
Debug.Print get_letter(60)
End Sub