在特定的Value / Text – VBA列中查找最后一个索引

我目前有一个sorting的列,看起来像这样:

Cat Cat Cat Cat Dog Dog Dog Dog 

我想find猫的最后一个索引(在本例中是4)和狗的最后一个索引(在这个例子中是8)

我尝试了以下内容:

 Dim Last_Index_F As Long With Sheets("Sheet1") Last_Index_F = Range("A:A").Find(what:="Cat", after:=Range("A2"), searchdirection:=x1Previous).row End With MsgBox (Last_Index_F) 

但是我得到了A2之后的猫的第一个索引。 有任何想法吗?

代码将是这样的。

 Sub test() Dim Last_Index_F As Long Dim Ws As Worksheet Dim rngDB As Range, rngF As Range Dim strAddress As String, n As Long Dim vR() Set Ws = Sheets("Sheet1") With Ws Set rngDB = .Range("a1", .Range("a" & Rows.Count).End(xlUp)) End With With rngDB Set rngF = .Find("Cat", after:=.Cells(.Rows.Count), LookIn:=xlValues, Lookat:=xlWhole) If rngF Is Nothing Then Else strAddress = rngF.Address Do n = n + 1 ReDim Preserve vR(1 To n) vR(n) = rngF.Row Set rngF = .FindNext(rngF) Loop While strAddress <> rngF.Address End If End With MsgBox WorksheetFunction.Max(vR) MsgBox vR(n) End Sub 

您只需要将“之后”移动到您正在search的列的末尾。

在我的例子中,我刚刚find最后一列A列

  Dim Last_Index_F As Long With Sheets("Sheet1") LastRow = Range("A" & Rows.Count).End(xlUp).Row Last_Index_F = Range("A:A").Find(what:="Cat", after:=Range("A" & LastRow), searchdirection:=xlPrevious).Row End With MsgBox (Last_Index_F)