查找与该值匹配的列中的最后一个单元格

时间:2018-04-15 06:33:52

标签: vba excel-vba excel

我有一个VBA脚本,用于搜索并查找列中单元格的值,然后向右偏移3列并放置时间戳。但是,我遇到了它在列中找到的第一个匹配的问题,但是我想让它为最后一个匹配而做。

Private Sub ExitButton_Click()

Dim cell As Range
    Set cell = Range("D1", Cells(Rows.Count, 4).End(xlUp)).Find(What:=Me.UsId.Value, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)

    If cell Is Nothing Then
        MsgBox "User ID '" & Me.UsId.Value & "' not found! Please enter the ID used while signing in.", vbExclamation
    Else
        cell.Offset(0, 3) = Format(Now(), "hh:mm AMPM")
    End If

    Me.UsId.Value = ""
    Me.UsId.SetFocus

End Sub

我对VBA脚本非常陌生,所以我不确定这是否可行。

1 个答案:

答案 0 :(得分:1)

你只需要从顶部开始并添加SearchDirection:= xlPrevious和After:= [第一个单元格] 。这曾经被称为锡罐循环。由于第一个单元格之前没有任何内容,因此它从底部开始查找。

如果您只想查看D列,

with columns("D")
    Set cell = .cells.Find(What:=Me.UsId.Value, After:=.cells(1), SearchDirection:=xlPrevious, _
                           LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
end with

If cell Is Nothing Then
    MsgBox "User ID '" & Me.UsId.Value & "' not found! Please enter the ID used while signing in.", vbExclamation
Else
    cell.Offset(0, 3) = Now
    cell.Offset(0, 3).numberformat = "hh:mm AM/PM"
End If
相关问题