Saturday, 21 April 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...