簡體   English   中英

Excel VBA中的循環引用

[英]Circular Reference in 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中調用'= Grade(A2)'后,我收到錯誤消息。有一個或多個循環引用,其中公式直接或間接引用其自己的單元格。

我想念什么?

您不執行帶有功能的動作。 您不應該嘗試修改單元格或其他任何內容。 (在您的代碼中,每次重新計算函數時,它將修改您選擇的任何單元格。)

您只需將值設置為函數,就好像它是一個變量一樣。 代碼完成后,它將函數的值返回給調用它的函數。 該函數可用於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

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM