VBA Range.Find 方法 return 值存在时无

VBA Range.Find Method return Nothing when value exists

我正在尝试获取包含特定值的单元格的地址:

dim MinAdrress as Range
Set MinAddress = DetractRow.Find(Min_1, , xlValues, xlWhole)

Min_1 为 0.23,DetractRow 范围包含以下值:

30% 26% 23% 27% -7%

所以 MinAddress 应该是范围内的第 3 个单元格。但是,在 Locals window 中,我将其视为 Nothing。我也试过没有可选参数(xlValues, xlWhole),结果相同。非常感谢任何输入

根据我的评论,我相信 Find 函数将匹配单元格的值,因为它是由该单元格格式化的。所以 0.23 不会找到 23% 除非你做一些额外的工作。例如,这将起作用:rng.Cells.Find("23%", rng.Cells(1), xlValues, xlWhole, xlRows, xlNext, True)。我听说过人们采取的各种非常奢侈的行动,尤其是。当谈到查找日期时(我什至听说有人阅读单元格格式,清除它们,然后在 Find 结束时重写它们)。

我不太喜欢 Find 函数。例如,您可能会竭尽全力创建一个值作为 String 以匹配特定的单元格格式,结果却发现您或其他人认为多一位小数会更好。沉没 Find 潜艇并不需要大量的深水炸弹。

我仍然赞成将值读入数组和 For ... Next 循环,尤其是 Value2 为您提供了选项,例如,以 Long 形式搜索日期,因此没有格式问题的风险。

这是为您准备的代码:

Dim v As Variant
Dim r As Long
Dim c As Long

'If DetractRow range is just one column
v = DetractRow.Value2
For r = 1 To UBound(v, 1)
    If v(r, 1) = Min_1 Then
        MsgBox "Gotcha at index " & CStr(r)
        Exit For
    End If
Next

'If DetractRow range is just one row
v = DetractRow.Value2
For c = 1 To UBound(v, 2)
    If v(1, c) = Min_1 Then
        MsgBox "Gotcha at index " & CStr(c)
        Exit For
    End If
Next

'If DetractRow range is more than one row and column
v = DetractRow.Value2
For c = 1 To UBound(v, 2)
    For r = 1 To UBound(v, 1)
        If v(r, c) = Min_1 Then
            MsgBox "Gotcha at index " & CStr(r) & _
                    ", " & CStr(c)
            Exit For
        End If
    Next
Next