首页 > 解决方案 > Excel VBA 自定义分数公式

问题描述

美好的一天,我正在尝试在 excel 中创建一个函数,该函数根据其他 4 个数字对数字进行评分,我正在为预算制作记分卡,因此我正在尝试完成以下操作:

我有一个包含以下表格的电子表格 在此处输入图像描述

现在我有 4 列,(K 到 N)“隐藏”,其中包含值 157、143、128、114。我想创建一个公式,将 A5 中的值与其他四列进行比较,然后将结果放在 J 列中。例如,我会将以下公式放在 J5 中

单元格 J5= 分数(A5、K5、L5、M5、N5)

为了获得评级,我创建了以下 VBA 代码:

Public Function Score(A As Integer, S1 As Integer, S2 As Integer, S3 As Integer, S4 As Integer) As String

    If A < S1 Then
        Score = "1"
    ElseIf S1 + 1 <= A < S2 Then
        Score = "2"
    ElseIf S2 + 1 <= A < S3 Then
        Score = "3"
    ElseIf S3 + 1 <= A < S4 Then
        Score = "4"
    ElseIf S4 + 1 <= A Then
        Score = "5"
    End If

End Function

有人可以告诉我哪里出错了吗?当我使用公式时出现#NUM错误

标签: excelvba

解决方案


如果这是您的第一次尝试,请尝试一下。您必须指定函数的返回值 -As String作为第一行的结尾。

Public Function Score() As String

    Dim iRow As Integer

    iRow = Application.Caller.Row
    A = Range("$A$5")
    S1 = Range("$K" & iRow)
    S2 = Range("$L" & iRow)
    S3 = Range("$M" & iRow)
    S4 = Range("$N" & iRow)

    If A < S1 Then
        Score = "1"
    ElseIf S1 + 1 <= A < S2 Then
        Score = "2"
    ElseIf S2 + 1 <= A < S3 Then
        Score = "3"
    ElseIf S3 + 1 <= A < S4 Then
        Score = "4"
    ElseIf S4 + 1 <= A Then
        Score = "5"
    End If

End Function

如果您想自己为功能选择五个单元格,例如=score(A5,F10, G10, H10, E10)

Public Function Score(A As Integer, S1 As Integer, S2 As Integer, S3 As Integer, S4 As Integer) As String

    If A < S1 Then
        Score = "1"
    ElseIf S1 + 1 <= A < S2 Then
        Score = "2"
    ElseIf S2 + 1 <= A < S3 Then
        Score = "3"
    ElseIf S3 + 1 <= A < S4 Then
        Score = "4"
    ElseIf S4 + 1 <= A Then
        Score = "5"
    End If

End Function

推荐阅读