Saturday, April 21, 2018

Get Cell reference for TOP 3 numbers within a Range (Excel VBA)

After getting the values, try looping through the range and assign range variables to these. Then print the addresses of the range variables:


Sub TestMe()
Dim firstVal As Double
Dim secondVal As Double
Dim thirdVal As Double
Dim rng As Range
Set rng = Worksheets(1).Range("A1:B10")
With Application
firstVal = Application.WorksheetFunction.Large(rng, 1)
secondVal = Application.WorksheetFunction.Large(rng, 2)
thirdVal = Application.WorksheetFunction.Large(rng, 3)
End With
Dim myCell As Range
Dim firstCell As Range
Dim secondCell As Range
Dim thirdCell As Range
For Each myCell In rng
If myCell.Value = firstVal And (firstCell Is Nothing) Then
Set firstCell = myCell
ElseIf myCell.Value = secondVal And (secondCell Is Nothing) Then
Set secondCell = myCell
ElseIf myCell.Value = thirdVal And (thirdCell Is Nothing) Then
Set thirdCell = myCell
End If
Next myCell
Debug.Print firstCell.Address, secondCell.Address, thirdCell.Address
End Sub

The check firstCell Is Nothing is done to make sure that in case of more than one top variable, the second one is assigned to the secondCell. E.g., if the range looks like this:


enter image description here


then the top 3 cells would be A2, A3, A1.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...