2017-10-20 122 views
1

我想寫一個簡單的Excel VBA函數從給定的單元格中取一個數字並分配一個等級,然後在當前活動單元格中寫入該值。在Excel VBA中的循環引用

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 

一旦調用在Excel「=級(A2)」我得到的錯誤消息 有一個或多個圓形的引用,其中一個公式是指其自身小區直接或間接的影響。

我錯過了什麼?

+3

變化'activecell.value =''到等級=' – Zerk

回答

3

您不執行具有功能的操作。你不應該嘗試修改單元格或任何東西。 (在您的代碼中,每次重新計算函數時,它都會修改您選擇的單元格。)

您只需將該值設置爲函數就好像它是一個變量。代碼完成後,它將函數的值返回給調用它的任何東西。該功能可用於Excel公式和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

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)