我有一个温度读数增加的文件,保持大致水平,然后减少。在细胞再次减少之前,我需要在高原(121
)找到最后一个值。我一直在尝试的代码是:
Set rng = Range("P22:Q217")
For Each cll In rng
If cll.Value > 121 Then
If cll.Row > first121row Then first121row = cll.Row
Exit For
End If
Next
MsgBox first121row
但是这会返回第一行,其值高于121
而不是最后一行。
我做错了什么,或者有更好的方法吗?
答案 0 :(得分:0)
从底部开始向上工作:
Sub dural()
For i = 217 To 22 Step -1
For Each a In Array("P", "Q")
If Cells(i, a).Value > 121 Then
MsgBox Cells(i, a).Row
Exit Sub
End If
Next a
Next i
End Sub
答案 1 :(得分:0)
您有一个已知的单元格范围要搜索(也可以动态获取),并且对标准工作表函数的调用可以检索该范围内的最大值。向后使用.Find
可能比循环更有效。
Sub last_MAX()
Dim mx As Double, rng As Range, lst As Range
Set rng = Range("P22:Q217")
mx = Application.Max(rng)
With rng
'normally .Find deserves some error control but we KNOW the value is in there
Set lst = .Find(what:=mx, after:=.Cells(1, 1), LookIn:=xlValues, lookat:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
Debug.Print "Last " & mx & "° found at row " & lst.row & " at " & lst.Address(0, 0)
End With
End Sub
通过在反向搜索之前检索最大值,我们可以放弃错误控制。对于VBA .Find
来说,这通常不是一个好主意,但我们知道在这种情况下价值就在那里。