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

时间:2016-07-13 10:32:02

标签: excel vba excel-vba

我有一张包含这些数据的Excel表格(附图) enter image description here

我希望选中的行(剩余表格) 所选行是埃尔比勒市(35,000IQD)的最后数据。

这意味着我希望特定(特定)城市的最后一行具有特定的(卡类型) (埃尔比尔市有两排数据卡类型35,000我想给我最后一个) 提前谢谢。

2 个答案:

答案 0 :(得分:1)

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

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

此代码的输出是

enter image description here

根据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

我将此代码放在工作表代码模块中:主数据表

答案 1 :(得分:0)

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

  • 使用方法Anastasiya-Romanova表示。
  • 使用自动过滤器和特殊细胞
  • 使用数组
  • 可能更多

这个方法使用find方法,它比循环更快。

我假设卡片类型是一个整数值而不是字符串,但如果它是一个字符串,只需将CardType更新为字符串并将值包装在引号中。

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