在列中查找最后一个值而不是每个值

时间:2016-06-26 15:12:57

标签: vba excel-vba excel

所以现在我有了这个代码来找到哪个人正在登录,并且只要他们使用用户表单选择他们的名字,就把NOW =()放在G列中。我唯一的问题是,如果此人在纸张上,它将替换所有行G条目,而不仅仅是最后一个。我只希望它将now =()函数放在B列中技术人员姓名的最后一次迭代的G列中。

Visual of description

   Private Sub CommandButton1_Click()

  Dim rngFound As Range
    Dim strFirst As String
    Dim strID As String
    Dim strDay As String

    strID = techname1.Value
    strDay = ""

    Set rngFound = Columns("B").Find(strID, Cells(Rows.Count, "B"), xlValues, xlWhole)
    If Not rngFound Is Nothing Then
        strFirst = rngFound.Address
        Do
            Application.Worksheets("SignOut").Cells(rngFound.Row, "G").Value = Now()
            Set rngFound = Columns("B").Find(strID, rngFound, xlValues, xlWhole)
        Loop While rngFound.Address <> strFirst
    End If

    Set rngFound = Nothing

    Unload Me


End Sub

1 个答案:

答案 0 :(得分:2)

要获得技术人员姓名的最后一次出现,您不必遍历该列。请尝试以下代码:

var

Private Sub CommandButton1_Click() Dim rngFound As Range Dim strFirst As String Dim strID As String Dim strDay As String strID = techname1.Value strDay = "" 'below line will give you the last occurrence of strID Set rngFound = Columns("B").Find(strID, Cells(Rows.Count, "B"), xlValues, xlWhole, , xlPrevious) If Not rngFound Is Nothing Then Application.Worksheets("SignOut").Cells(rngFound.Row, "G").Value = Now() End If Set rngFound = Nothing Unload Me End Sub 函数的语法是:

Range_Object.Find(What,After,LookIn,LookAt,SearchOrder,SearchDirection,MatchCase,MatchByte,SearchFormat)

此处, SearchDirection 是一个可选参数,用于指定在范围内搜索时的搜索方向,并可以采用以下两个值之一:

  • xlNext - &gt;搜索范围
  • 中的下一个匹配值
  • xlPrevious - &gt;搜索范围
  • 中的上一个匹配值

这两个 xlNext 是默认的。当您没有提及它时,查找使用 xlNext 并在范围为列的情况下从上到下进行搜索。因此,要最后一次出现字符串,请使用 xlPrevious ,它将在列中从下到上进行搜索。