I am trying and failing at making a IF/AND statement in a userform work. I want to be able to add the same Last Name and different First Name to a dynamic list but my current code (below) is catching this as a duplicate value. I am able to add a fully unique Frist and Last Name without encountering any issues.
In my code below I pull the first name from TextBox2/Num2 and the last name from TextBox3/Num3
Ex: Adding John Doe to the list that already has Jane Doe will catch as a duplicate for the Last Name.
Current State of my worksheet
Dim Num1 As Long
Dim Num2 As Long
Dim Num3 As Long
On Error Resume Next
Num1 = Application.WorksheetFunction.Match(Me.TextBox1.Value, ws.Range("A2:A500000"), 0)
Num2 = Application.WorksheetFunction.Match(Me.TextBox2.Value, ws.Range("B2:B500000"), 0)
Num3 = Application.WorksheetFunction.Match(Me.TextBox3.Value, ws.Range("C2:C500000"), 0)
On Error GoTo 0
If Num1 > 0 Then
MsgBox "Error! Duplicate EID detected", , "Duplicate Detected"
Exit Sub
End If
If Num2 > 0 And Num3 > 0 Then
MsgBox "Error! Duplicate NAME detected", , "Duplicate Detected"
Exit Sub
End If
Use WorksheetFunction.CountIfs
instead of Match
and check if the result is greater than 0. That will search for the combination of the first and last name on the same row.
Dim firstName As String
firstName = Me.TextBox2.Value
Dim lastName As String
lastName = Me.TextBox3.Value
If WorksheetFunction.CountIfs(ws.Range("B:B"), firstName, ws.Range("C:C"), lastName) > 0 Then
MsgBox "Error! Duplicate NAME detected", , "Duplicate Detected"
Exit Sub
End If
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.