首页 > 解决方案 > 第二高值

问题描述

我已经编写了代码,以便获得第一个和第二个最高值。

我能够获得第一个最高值。

但是,我无法获得第二高的价值。

我正在使用 VBA 作为工具。

Sub abc()
    Dim x As Long
    Dim y As Long
    Dim lr As Integer
    Dim minvalue As Double, maxvalue As Double

    Worksheets("Player_Statistics").Activate

    lr = Cells(Rows.Count, 1).End(xlUp).Row

    For x = 2 To lr
        pn = Cells(x, 1).Value
        pp = Cells(x, 2).Value
        pa = Cells(x, 7).Value

        If Range("b" & x) = "Allrounder" Then
            Range("g" & x) = (Range("c" & x) * Range("d" & x)) * 10000 / (Range("e" & x) * Range("f" & x))
        ElseIf Range("b" & x) = "Batsman" Then
            Range("g" & x) = Range("c" & x) * Range("d" & x)
        ElseIf Range("b" & x) = "Bowler" Then
            Range("g" & x) = Range("e" & x) * Range("f" & x)
        End If

        If pp = "Allrounder" And pa > maxvalue Then
            Range("a14").Value = pn
            Range("b14").Value = pa
            maxvalue = Range("b14")
        End If
    Next x

    For y = 2 To lr
        If pp = "Allrounder" And pa > minvalue And pa < maxvalue Then
            Range("a15").Value = pn
            Range("b15").Value = pa
        End If
    Next y
End Sub

我的数据: 在此处输入图像描述

我没有收到任何错误消息。但是,价值也没有被打印出来。

请让我知道我在哪里遗漏了一些东西。

希望得到一些积极的回应。

问候,艾尤布

标签: excelvba

解决方案


你的代码也没有给我最高的数字......

再次单步执行您的代码,您就会明白原因。

我认为您需要三个不同的循环来:

  • 计算 G 列中的分数
  • 获得最高数
  • 获得第二高的数字

这对我有用:

Sub abc()
    Dim x As Long
    Dim lr As Integer
    Dim minvalue As Double
    Dim maxvalue As Double
    Dim pn As String
    Dim pp As String
    Dim pa As Double

    Worksheets("Player_Statistics").Activate

    lr = Cells(Rows.Count, 1).End(xlUp).Row

    For x = 2 To lr
        pn = Cells(x, 1).Value
        pp = Cells(x, 2).Value
        pa = CDbl(Cells(x, 7).Value)

        If Range("b" & x) = "Allrounder" Then
            Range("g" & x) = (Range("c" & x) * Range("d" & x)) * 10000 / (Range("e" & x) * Range("f" & x))
        ElseIf Range("b" & x) = "Batsman" Then
            Range("g" & x) = Range("c" & x) * Range("d" & x)
        ElseIf Range("b" & x) = "Bowler" Then
            Range("g" & x) = Range("e" & x) * Range("f" & x)
        End If
    Next

    For x = 2 To lr
        pn = Cells(x, 1).Value
        pp = Cells(x, 2).Value
        pa = CDbl(Cells(x, 7).Value)
        If pp = "Allrounder" And pa > maxvalue Then
            maxvalue = pa
            Range("a14").Value = pn
            Range("b14").Value = CStr(pa)
        End If
    Next

    For x = 2 To lr
        pn = Cells(x, 1).Value
        pp = Cells(x, 2).Value
        pa = CDbl(Cells(x, 7).Value)
        If pp = "Allrounder" And pa > minvalue And pa < maxvalue Then
            minvalue = pa
            Range("a15").Value = pn
            Range("b15").Value = CStr(pa)
        End If
    Next
End Sub

推荐阅读