2017-06-14 132 views
2

我有下面的代碼,應該找到範圍中的第1,2,3個和第4個最高值。Excel VBA - 查找範圍內的最高值和後續值

它目前是非常基本的,我有它提供了一個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 
+2

另一種方法將排序範圍,然後拿起你的價值:) –

+0

你真的需要在VBA中做到這一點? –

回答

7

使用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 
+1

+++該死的該死! –

+0

是的,這很好。謝謝! – sbagnato

+0

@Jeeped。斯科特是對的。 Excel公式標記不是爲此目的:) –

2

你必須通過上述Scott Craner提出一個更好的方法。但是,要回答您的問題,您只返回有限數量的值,因爲您將覆蓋值而不將原始值轉換爲較低的值。

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)