簡體   English   中英

獲取范圍內前3個數字的單元格引用(Excel VBA)

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

我在Excel中有一個帶有數字的單元格范圍(假設A1:Z1 ),我想獲得三個最高的數字。 我在這里找到的問題的這一部分的答案- 查找范圍內的最高值和后續值

但我也想獲得這些值的單元格引用。

firstVal = Application.WorksheetFunction.Large(rng,1)
secondVal = Application.WorksheetFunction.Large(rng,2)        
thirdVal = Application.WorksheetFunction.Large(rng,3)

獲取值后,嘗試遍歷范圍並為這些變量分配范圍變量。 然后打印范圍變量的地址:

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

檢查firstCell Is Nothing是否完成以確保在多個頂部變量的情況下,第二個變量被分配給secondCell。 例如,如果范圍如下所示:

在此處輸入圖片說明

那么前3個單元格將是A2, A3, A1

效率不高,但是您可以指定要返回的地址數:

Sub Tester()

    Debug.Print Join(Largest(ActiveSheet.Range("A1:Z1"), 3), ", ")

End Sub


Function Largest(rng As Range, howMany As Long)
    Dim rv(), n As Long, c As Range, lg
    ReDim rv(1 To howMany)
    n = 1
    Do
        lg = Application.Large(rng, n)
        For Each c In rng
            If c.Value = lg Then
                If IsError(Application.Match(c.Address, rv, 0)) Then
                    rv(n) = c.Address
                    n = n + 1
                    Exit For
                End If
            End If
        Next c
    Loop While n <= howMany
    Largest = rv
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM