Finding highest and subsequent values in a range

倖福魔咒の 提交于 2019-11-29 15:21:50

Use Application.WorksheetFunction.Large():

Sub Macro1()

Dim rng As Range, cell As Range
Dim firstVal As Double, secondVal As Double, thirdVal As Double, fourthVal As Double

Set rng = [C4:C16]


firstVal = Application.WorksheetFunction.Large(rng,1)
secondVal = Application.WorksheetFunction.Large(rng,2)        
thirdVal = Application.WorksheetFunction.Large(rng,3)
fourthVal = Application.WorksheetFunction.Large(rng,4)

MsgBox "First Highest Value is " & firstVal
MsgBox "Second Highest Value is " & secondVal
MsgBox "Third Highest Value is " & thirdVal
MsgBox "Fourth Highest Value is " & fourthVal

End Sub

You have a better method suggested by Scott Craner above. However, to answer your question, you are only returning a limited number of values because you are overwriting the values without shifting the original values to a lower rank.

Dim myVALs As Variant
myVALs = Array(0, 0, 0, 0, 0)

For Each cell In rng
    Select Case True
        Case cell.Value2 > myVALs(0)
            myVALs(4) = myVALs(3)
            myVALs(3) = myVALs(2)
            myVALs(2) = myVALs(1)
            myVALs(1) = myVALs(0)
            myVALs(0) = cell.Value2
        Case cell.Value2 > myVALs(1)
            myVALs(4) = myVALs(3)
            myVALs(3) = myVALs(2)
            myVALs(2) = myVALs(1)
            myVALs(1) = cell.Value2
        Case cell.Value2 > myVALs(2)
            myVALs(4) = myVALs(3)
            myVALs(3) = myVALs(2)
            myVALs(2) = cell.Value2
        Case cell.Value2 > myVALs(3)
            myVALs(4) = myVALs(3)
            myVALs(3) = cell.Value2
        Case cell.Value2 > myVALs(4)
            myVALs(4) = cell.Value2
        Case Else
            'do nothing
    End Select
Next cell

Debug.Print "first: " & myVALs(0)
Debug.Print "second: " & myVALs(1)
Debug.Print "third: " & myVALs(2)
Debug.Print "fourth: " & myVALs(3)
Debug.Print "fifth: " & myVALs(4)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!