VBA - 获取与范围内的最大值关联的字符串

VBA - Get String Associated with Max Value in Range

我正在 excel 中编写宏,需要获取与某个范围内的最大值关联的字符串或文本。

我的范围看起来像这样:

一个 | B
CR1 | 2.33
CR2 | 5.1
CR3 | 10.0
CR4 | 3.8

我能够在 B 列中找到 MAX 值,但现在我需要在 A 列中找到关联的字符串。所以在这种情况下,给定 B3 (10.0) 是最大值,我想提取 'CR3'.

所以我提取最大值的代码是:

 Set myRange = Application.InputBox( _
 prompt:="Please select the Range.", Title:="Graph Range", Type:=8)
 highestNum = Application.WorksheetFunction.Max(myRange)

如何获取 A 列中的关联字符串? 我试过使用 .Address,但这并没有帮助我。

提前致谢!



!!!!!!!! Edit/Update - 已解决:!!!!!!!

正如另一位贡献者所建议的,我需要使用 inded + Match。请参阅下面的解决方案。

Set myRange = Application.InputBox( _
prompt:="Please select the Primary KPI 'Lift' Data to Graph.", Title:="Graph Range", Type:=8)

Set rngColumn2 = myRange.Areas(2)

highestNum = Application.WorksheetFunction.Max(myRange)

test = Application.WorksheetFunction.Index(myRange, Application.WorksheetFunction.Match(highestNum, rngColumn2, 1), 1)

您只需要一个 index(Match,Match) 函数。 它将查看 B 中的最高数字和 return A.

您可以使用 Range.Find() 来 return 找到最大值的单元格。

然后使用偏移量 return 单元格直接向左的值:

 Dim mtch As Range
 Set myrange = Application.InputBox( _
 prompt:="Please select the Range.", Title:="Graph Range", Type:=8)
 highestNum = Application.WorksheetFunction.Max(myrange)
 Set mtch = myrange.Find(highestNum)
 Debug.Print mtch.Offset(, -1).Value

编辑

您似乎遇到了 rounding/floating 小数问题。为了帮助解决这个问题,我们需要更改为 For Each 循环并将每个值加载到另一个双精度值中,这样舍入是相同的:

Dim mtch As Range
Dim highestNum As Double
Dim t As Double
Dim myrange As Range
 Set myrange = Application.InputBox( _
 prompt:="Please select the Range.", Title:="Graph Range", Type:=8)
 highestNum = Application.WorksheetFunction.Max(myrange)
 t = Range("B3").Value
 r = t = highestNum
 For Each mtch In myrange
    t = mtch.Value
    If t = highestNum Then
        Debug.Print mtch.Offset(, -1).Value
        Exit For
    End If
Next mtch

只是想尝试一下 Scott 的解决方案:

With Application.InputBox(prompt:="Please select the Range.", Title:="Graph Range", Type:=8)
    Debug.Print Cells.Find(Application.WorksheetFunction.Max(.Cells)).Offset(, -1).Value
End With