查找特定数据范围的最后一行excel

我有一个包含这些数据的Excel工作表(附图) 在这里输入图像说明

我想要在(剩余表单)中选中的行选中的行是在埃尔比勒市的(35,000IQD)的最后一个数据。

这意味着我要在具体(卡片types)(具体)城市中的最后一行(卡片types为35,000的埃尔比勒市的两行数据我要给我最后一个)预先感谢。

如果我正确理解你的问题,那么你试试这个代码:

Sub MatchingCityAndCardType1() Dim City As String, i As Long, Last_Row As Long Last_Row = Cells(Rows.Count, "E").End(xlUp).Row For i = Last_Row To 2 Step -1 City = Cells(i, "C").Value If City = "erbil" And Mid(Cells(i, "E"), 1, 6) = "35,000" Then MsgBox "The card remaining of " & City & " city with card type " _ & Cells(i, "E").Value & " is " & Cells(i, "J").Value & "." Exit For End If Next i End Sub 

这个代码的输出是

在这里输入图像说明


根据pashew在下面评论中的要求,这个代码应该可以工作

  Sub MatchingCityAndCardType2() Dim City As String, i As Long, Last_Row As Long Last_Row = Cells(Rows.Count, "E").End(xlUp).Row For i = Last_Row To 2 Step -1 City = Cells(i, "C").Value If City = "erbil" And Mid(Cells(i, "E"), 1, 6) = "35,000" Then 'Set the range destination, Range(“A2”), depending on which 'range you want in Sheets(“Remaining”) Rows(i).EntireRow.Copy Destination:=Worksheets("Remaining").Range("A2") Exit For End If Next i End Sub 

我把这段代码放在工作表代码模块中: 主数据表

有几种方法可以解决这个问题:

  • 用Anastasiya-Romanova的方法说过。
  • 使用自动filter和特殊的细胞
  • 使用数组
  • 也许更多

这个使用循环更快的find方法。

我假设卡的types是一个整数值,而不是string,但是如果它是一个string,只是将CardType更新为string,并将值包含在引号中。

 Sub FindLastRow() Dim city As String, FirstAddress As String Dim CardType As Long Dim rng As Range Dim a city = "erbil" CardType = 35000 With ThisWorkbook.Sheets("Main Data Sheet") Set rng = .Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 10)) End With With rng Set a = .Find(what:=city, SearchDirection:=xlPrevious) If Not a Is Nothing Then FirstAddress = a.Address Do If a.Offset(0, 2) = CardType Then ' Update this part with whatever you want to do to the last row MsgBox a.Address Exit Do Else Set a = .FindNext(a) End If Loop While Not a Is Nothing And a.Address <> FirstAddress End If End With End Sub