如何将数据验证放在Excel中重复值的列中?

时间:2019-07-05 09:01:36

标签: excel vba excel-formula

我必须将数据验证放在“ B”列中以获取重复的文本值。 因此用户无法在“ B”列中输入重复的值。

我为此使用了自定义公式,效果很好,但是有一个局限性。 当用户复制和粘贴值时,它不起作用,仅当用户通过键入单元格输入值时,它才起作用。

我的自定义公式: db.use_collection.aggregate( [ { $project : { _id: 0, user_name : 1 } } ] )

我期望一种解决方案,即使用户也无法通过复制和粘贴输入重复的值。

1 个答案:

答案 0 :(得分:1)

您可以在工作表中添加Worksheet.Change event并在其中测试重复项。如果插入(粘贴或键入)副本,则只需.Undo粘贴。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim AffectedRange As Range
    Set AffectedRange = Intersect(Target, Me.Columns("B"))

    If Not AffectedRange Is Nothing Then  'if at least one cell in column B was changed
        Dim Cell As Range
        For Each Cell In AffectedRange 'loop throuh all changed cells in column B
            If Application.WorksheetFunction.CountIf(Me.Columns("B"), Cell.Value) > 1 Then 'test if it is a duplicate
                Application.Undo 'undo the paste/insert
                MsgBox "Duplicates are not allowed", vbExclamation
                Exit For
            End If
        Next Cell
    End If
End Sub