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?
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
Excel公式替代方案,以防万一:
=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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.