限制 Excel VBA 中的重复值

Restricting duplicate values in Excel VBA

与前一行中的第 2 列和第 5 列相比,我需要限制用户在第 2 列和第 5 列中输入重复值

如果与前一行中这些列的值相比,第 2 列或第 5 列有重复项,我的代码会限制输入重复项。

我的目标是在两列具有重复值时发出警告/操作。

截图示例:

VBA “工作表 1”中的代码:

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

在第 2 列上使用 Find、FindNext,然后检查第 5 列中的值。注意 - 这将在任何行中找到重复项,而不仅仅是前一行。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    
    Const PK1 = 2 ' Primary Keys
    Const PK2 = 5

    Dim V1, V2, rng As Range, first As String
    
    If (Target.Column = PK1) Or (Target.Column = PK2) Then
        V1 = Me.Cells(Target.Row, PK1) ' B
        V2 = Me.Cells(Target.Row, PK2) ' E
        If V1 = "" Or V2 = "" Then Exit Sub
    Else
        Exit Sub
    End If
    
    With Me.Columns(PK1)
        Set rng = .Find(V1, lookat:=xlWhole, LookIn:=xlValues)
        If Not rng Is Nothing Then
            first = rng.Address
            Do
               If (rng.Row <> Target.Row) And (Cells(rng.Row, PK2) = V2) Then
                  MsgBox "Duplicate Value " & V1 & "," & V2, vbExclamation, "Row " & rng.Row
                  Target.Select
                  Application.EnableEvents = False
                  Target.Clear
                  Application.EnableEvents = True
                  Exit Do
               End If
               Set rng = .FindNext(rng)
            Loop While rng.Address <> first
         End If
    End With
    
End Sub