简体   繁体   English

如何在列中查找值高于特定水平的最后一个单元格

[英]How to find last cell with value above certain level in a column

I have a file with temperature readings that increase, stay roughly level, then decrease. 我有一个温度读数升高,大致保持水平然后降低的文件。 I need to find the last value at the plateau ( 121 ) before the cells decrease again. 我需要在单元格再次减少之前在平稳期( 121 )找到最后一个值。 The code I've been trying is: 我一直在尝试的代码是:

    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  

But this returns the first row with a value above 121 instead of the last row. 但这会返回第一行的值大于121而不是最后一行。

What am I doing wrong, or is there a better approach to this? 我在做什么错,还是有更好的方法呢?

Start from the bottom and work upwards: 底部开始并向上工作:

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

You have a known range of cells you want to search (could also be dynamically obtained) and a call to a standard worksheet function can retrieve the maximum value in the range. 您具有要搜索的已知单元格范围(也可以动态获取),并且对标准工作表函数的调用可以检索该范围内的最大值。 Using .Find backwards may be more efficient than a loop. 使用.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

By retrieving the maximum value just prior to the reverse search we can forego error control. 通过在反向搜索之前检索最大值,我们可以放弃错误控制。 That is not normally a good idea with a VBA .Find but we know the value is there in this case. 这不是通常与VBA一个好主意.Find但是我们知道价值是有在这种情况下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM