excel - 获取范围内前 3 个数字的单元格引用(Excel VBA)

标签 excel vba

我在 Excel 中有一个带有数字的单元格范围(比如说 A1:Z1 ),我想获得三个最高的数字。回答我在这里找到的这部分问题 - Finding highest and subsequent values in a range

但我也想获得这些值的单元格引用。

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。例如,如果范围如下所示:

enter image description here

那么前 3 个单元格将是 A2, A3, A1 .

关于excel - 获取范围内前 3 个数字的单元格引用(Excel VBA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56485992/

相关文章:

vba - excel vba函数可以打开文件吗?

excel - 将两个vba代码合二为一

algorithm - 不确定数量的变量的 VBA 排列

excel - VBA 代码可以在 MS 应用程序之外运行吗?

arrays - VBA代码不会将数组写入范围,只有第一个元素

Excel 自动化。需要从范围中选择多个项目

excel - 如何预测数字序列,即 Excel?

vba - Visual Basic for Applications 中的文本模板引擎/函数

具有日期条件的表的 vba excel AdvancedFilter 方法不起作用

VBA 展望。尝试从电子邮件正文中提取特定数据并导出到 Excel