I need to restrict users entering duplicate values in the columns 2 and 5 compared to the columns 2 and 5 in a previous row
My code restricts entering duplicates if either Column 2 OR Column 5 has duplicates compared to the values for these columns in a previous row.
My goal is to have a warning / action when both columns have duplicate values.
VBA code in "Sheet1":
Private Sub Worksheet_Change(ByVal Target As Range)
With Target
If (.Column <> 2 And .Column <> 5) Or .Cells.Count > 1 Then Exit Sub
If WorksheetFunction.CountIfs(Columns(.Column), .Value) > 1 Then
Application.DisplayAlerts = False
.ClearContents
Application.DisplayAlerts = True
MsgBox "Duplicate value!"
End If
End With
End Sub

.Cells.Count > 1 Then Exit Substops the code. It should be necessary to better explain what you try accomplishing. In your question you ask about duplicates, now you talk about the "previous row"... Did you want saying previous rows? Meaning existing values in those two columns? Even so, you should be better clarifying what what you want. I must confess that I still not understand what you really need... Where my above interpretation suggestion is wrong? I mean, in my first comment...Targetcontain? I mean isn't only one cell modified (column B OR E)?. 2. If only one cell, but it must be checked against both columns, should it check only the row above the one where theTargetexists? 3. Should the event allow aTargedconsisting of a discontinuous range with two cells (Range("B3, E3"))? If not the row above to be the reference, your example in not so elocvent...