Finding highest and subsequent values in a range

前端 未结 2 1027
悲哀的现实
悲哀的现实 2020-12-21 06:47

I have the below code which is supposed to find the 1st, 2nd, 3rd, and 4th highest values in a range.

It is currently very basic, and I have it providing the values

2条回答
  •  自闭症患者
    2020-12-21 07:43

    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)
    

提交回复
热议问题