第二最高和第一最高价值

时间:2019-07-28 15:13:05

标签: excel vba

我有五个球员,我需要从中选出两个最佳球员。

样本数据。 平均姓名命中率 苏拉夫40.73 萨钦44.83 阿尼尔10.54 Zaheer 12 拉胡尔39.17

我尝试过循环。但是,我无法获得所需的答案。

下面是代码。

在此处输入代码。


    Dim rng As Range, cell As Range
    Dim highestValue As Double, secondHighestValue As Double

    Sub nss()


    Set rng = Selection
    highestValue = 0
    secondHighestValue = 0

    'Find Highest Value
    For Each cell In rng

    Next cell

    If cell.Value > highestValue Then highestValue = cell.Value

    'Find Second Highest Value
    For Each cell In rng

    Next cell

    If cell.Value > secondHighestValue And cell.Value < highestValue Then secondHighestValue = cell.Value

    MsgBox "Second Highest Value is " & secondHighestValue


    End Sub

我收到错误消息“运行时错误91”,“对象变量或未设置块”

此外,我还在寻找要打印的第二高值之后的第一个最高值。

希望获得一些好的结果。

关于, 艾尤布

1 个答案:

答案 0 :(得分:0)

遵循BigBen的技巧,您需要在现有的If循环内移动For Each语句。您还需要在每个If语句后加上一个End If,否则您的宏仍然无法使用。

最重要的是,不要在Dim之外声明变量(Sub),除非您希望在当前模块中重新使用它们(即“模块级变量”)

我还扩展了您的MsgBox以打印第一个最大值(根据您的要求)。

Sub nss()
    Dim rng As Range, cell As Range
    Dim highestValue As Double, secondHighestValue As Double

    Set rng = Selection
    'highestValue = 0
    'secondHighestValue = 0

    'Find Highest Value
    For Each cell In rng
        If cell.Value > highestValue Then
            highestValue = cell.Value
        End If
    Next cell

    'Find Second Highest Value
    For Each cell In rng
        If cell.Value > secondHighestValue And cell.Value < highestValue Then
            secondHighestValue = cell.Value
        End If
    Next cell

    MsgBox "Second Highest Value is " & secondHighestValue & vbNewLine & "First Highest Value is " & highestValue
End Sub

P.S。另外,您可以使用Large函数...

Sub nss()
    Dim rng As Range, cell As Range
    Dim highestValue As Double, secondHighestValue As Double

    Set rng = Selection

    'Find Highest Value
    highestValue = Application.WorksheetFunction.Large(rng, 1)

    'Find Second Highest Value
    secondHighestValue = Application.WorksheetFunction.Large(rng, 2)

    MsgBox "Second Highest Value is " & secondHighestValue & vbNewLine & "First Highest Value is " & highestValue
End Sub