1
votes

I'm trying to write a simple Excel VBA function to take a number from a given cell and assign a grade then write the value in the current active cell.

Public Function Grade(rng As Range)
    Dim number As Double
    number = rng.Value

    If number >= 75 Then
        ActiveCell.Value = "A"
    ElseIf number >= 60 Then
        ActiveCell.Value = "B"
    ElseIf number >= 50 Then
        ActiveCell.Value = "C"
    ElseIf number >= 45 Then
        ActiveCell.Value = "D"
    ElseIf number < 45 Then
        ActiveCell.Value = "F"
    End If

End Function

Upon calling '=Grade(A2)' in Excel I get the error message There are one or more circular references where a formula refers to its own cell either directly or indirectly.

What am I missing?

2
change activecell.value = to grade = - Zerk

2 Answers

3
votes

You don't perform actions with functions. You shouldn't try to modify cells or anything. (In your code, every time the function is recalculated, it would be modifying whatever cell you have selected.)

You just need to set the value to the function as if it was a variable. When the code is finished, it returns the value of the function to whatever called it. The function is available for use in Excel formulas and in VBA.

Public Function Grade(rng As Range)
Dim number As Double
number = rng.Value

If number >= 75 Then
    Grade = "A"
ElseIf number >= 60 Then
    Grade = "B"
ElseIf number >= 50 Then
    Grade = "C"
ElseIf number >= 45 Then
    Grade = "D"
ElseIf number < 45 Then
    Grade = "F"
End If

End Function
1
votes

Excel formula alternatives just in case:

=LookUp(A1,{0,45,50,60,75;"F","D","C","B","A"})

=Char(71-Match(A1,{0,45,45,50,60,75}))

=Mid("FFFFFFFFDCCBBBAAAAAA",A1/5,1)