我正在尝试使用 VBA 中的 Range.Find 方法来定位具有“真”值的最接近的前一个行号。
例如,在 X 列中,将有一个“真”值(第 35 行),10 行“假”,然后再次“真”(第 46 行)。
当我到达循环中的第 46 行时,我需要执行 range.find 并返回第 35 行。
我正在使用的代码是这样的:
Worksheets("Data").Cells.Find(True, searchorder:=xlByColumns, searchdirection:=xlNext).Row
发生的事情是我只找到第一个“真实”值(在本例中为第 2 行)或最后一个“真实”值(第 24 行,xxx 行),因为我改变了搜索方向。
我该怎么做才能只找到以前最“真实”的值?
最佳答案
您可以使用 After
找到前一行的 True Find
中的参数方法结合 xlPrevious
作为 SearchDirection
.根据您的评论,我已更新代码以将其添加到循环中。
自从您发布代码以来,我已将答案编辑到您的代码中。
Sub Main()
Dim iCurRow As Long
Dim iCounter As Long
Dim iLastRow As Long
Dim iTempRow As Long
Dim iPreviousRow As Long
Dim iChangeCol As Long
Dim ws As Worksheet
Set ws = Worksheets("Data")
With ws
iChangeCol = .Cells.Find(what:="Change Over?", searchorder:=xlByColumns, searchdirection:=xlNext).Column
iLastRow = .Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
iPreviousRow = 2
For iCounter = 3 To iLastRow
If .Cells(iCounter, iChangeCol).Value = True Then
iTempRow = .Cells.Find(what:=True, After:=.Cells(iCounter, iChangeCol), searchorder:=xlByColumns, searchdirection:=xlPrevious).Row
iPreviousRow = iTempRow
End If
Next iCounter
End With
End Sub
关于excel - 在 VBA 中使用 Range.Find 仅查找前一个值 x?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33611136/