Excel VBA自定义分数公式

时间:2018-11-15 04:53:59

标签: excel vba

早上好,我正在尝试在excel中创建一个函数,该函数根据其他4个数字对一个数字进行评分,我正在为预算制定一个计分卡,因此我尝试完成以下任务:

我有一个包含以下表格的电子表格 enter image description here

现在我有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错误

3 个答案:

答案 0 :(得分:1)

如果这是您的第一项尝试,请尝试一下。您必须指定函数的返回值-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

答案 1 :(得分:0)

我终于明白了。首先,我忘记了我正在使用数以百万计的数字,因此long无法正常工作,我不得不使用Public Function ScoreDown(A As Long, S1 As Long, S2 As Long, S3 As Long, S4 As Long) As String If A > S1 Then Score = "1" ElseIf S1 >= A And A > S2 Then Score = "2" ElseIf S21 >= A And A > S3 Then Score = "3" ElseIf S3 >= A And A > S4 Then Score = "4" ElseIf S4 >= A Then Score = "5" End If End Function ,但得到的结果却不是正确的,所以我决定尝试规定之间。这是我的结果: 该函数规定,A越低,评级越好

ap = {  
   "api_version":"3.1",
   "metadata":{  
      "total_matches":1,
      "kind":"vm",
      "length":1,
      "offset":true
   }

答案 2 :(得分:0)

最简单的解决方案-我认为并且如果不使用VBA的解决方案还可以-将在K列之前再插入一个隐藏列,然后输入任何非常大的数字(只需确保A列中的值始终为低于该值。

然后在J3中输入以下公式:

=MATCH(A3,K3:O3,-1)