【发布时间】:2017-06-14 17:49:16
【问题描述】:
我有下面的代码,它应该在一个范围内找到第 1、第 2、第 3 和第 4 个最高值。
它目前非常基本,我让它在 MsgBox 中提供值,所以我可以确认它正在工作。
但是,它只查找最高值和次高值。第三个和第四个值返回为 0。我缺少什么?
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]
For Each cell In rng
If cell.Value > firstVal Then firstVal = cell.Value
If cell.Value > secondVal And cell.Value < firstVal Then secondVal =
cell.Value
If cell.Value > thirdVal And cell.Value < secondVal Then thirdVal =
cell.Value
If cell.Value > fourthVal And cell.Value < thirdVal Then fourthVal =
cell.Value
Next cell
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
【问题讨论】:
-
另一种方法是对范围进行排序,然后获取您的值:)
标签: excel vba worksheet-function