I have a list that contains Employee ID in Col A, First Name in Col B, Last Name in Col C. I am needing to write a macro that gives a userform to input First and Last Name and from there it will put the proper Employee ID into the first unused cell in Col E and then loop back to the userform.
I already know how to build the Userform and will have two buttons on it one that reads "Next" and one that reads "End". The "Next" button will loop the Userform and the "End" will just close the Userform.
Plan on leaving the Userform named Userform1 and naming the input boxes as "FirstName" and "LastName". So I know that to reference these from the macro I would call for Userform1.FirstName.Value or Userform1.LastName.Value depending on which part I need at the moment.
The part I am not sure on is how to the matching of two variables and then looking to the left for the ID. I can move the ID Col to be after the name Cols if that helps but I am still not sure how to write so that both names must match.
As for error trapping I planned on having a MsgBox state "There are no matching entries." If the person does not exist in the list. However I am unsure of how to handle the super unlikely but possible situation of if two people on the list have the same name. So any suggestions for this would be greatly appreciated.
I am using Excel 2013.
Try this for the next button
Private Sub NextButton_Click()
Dim emptyRow As Long
Dim matchFound As Boolean
Dim matchCount As Long
Dim matchRow As Long
Dim i As Long
'Determine the first empty cell in column E
If Cells(1, 5).Value = "" Then
emptyRow = 1
Else
emptyRow = Cells(Columns(5).Rows.Count, 5).End(xlUp).Row + 1
End If
matchFound = False
matchCount = 0
matchRow = 0
'Loop through all of rows that have an employee id
For i = 1 To Cells(Columns(1).Rows.Count, 1).End(xlUp).Row
If (UCase(FirstName.Value) = UCase(Cells(i, 2).Value)) And (UCase(LastName.Value) = UCase(Cells(i, 3).Value)) Then
matchCount = matchCount + 1
matchRow = i
matchFound = True
End If
Next
'Alert user of any errors
If matchFound = False Then
MsgBox ("There are no matching entries")
ElseIf matchCount > 1 Then
MsgBox ("There were multiple matches")
Else
'If there are no errors add employee id to the list
Cells(emptyRow, 5).Value = Cells(matchRow, 1).Value
emptyRow = emptyRow + 1
End If
'Clear the userform
FirstName.Text = ""
LastName.Text = ""
End Sub
I'm not sure what the best course of action to take if there are multiple matches, so for now I just included a message to alert the sure. It wouldn't be hard to change the code to track each of the matched rows instead of just the last one.