VBA迭代不返回值

时间:2015-01-02 22:15:50

标签: excel excel-vba vba

我正在编写一个非常简单的子流程来为数字等级值指定一个字母等级。我有一个循环,我试图将单元格值设置为我的函数的输出。这似乎是一个非常简单的任务,但我的循环的前两次迭代不分配任何值。我的循环只经过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

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

4 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

或使用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

答案 3 :(得分:-1)

因为你从第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