Josh
Josh

Reputation: 19

Find last value in column instead of every value

So right now I have this code to find which person is signing in and put NOW=() in column G whenever they use the user form to select their name. The only problem I am having is that if the person is on the sheet previously it replaces all of the row G entries, not just the last one. I only want it to place the now=() function in the G column of the last iteration of the technicians name in the B column.

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

Upvotes: 1

Views: 182

Answers (1)

Mrig
Mrig

Reputation: 11727

To get the last occurrence of technicians name you do not have to loop through the column. Try below code:

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

Syntax of Find function is:

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

Here, SearchDirection is an optional parameter that specifies the search direction while searching in the range and can take one of the follwing two values:

  • xlNext --> search for the next matching value in range
  • xlPrevious --> search for previous matching value in range

Of these two xlNext is default. When you do not mention it, Find uses xlNext and searches from top to bottom in your case where range is a column. So to get the last occurrence of string use xlPrevious which will search from bottom to top in a column.

Upvotes: 2

Related Questions