当用户复制粘贴数据时,Excel 中的数据验证不起作用。
我希望当用户在某一列中粘贴重复数据时抛出一条错误消息。
我正在使用以下代码(另一种选择),但这不是我想要的。我希望在用户插入数据时检查这一点,如果有任何问题,则抛出错误消息。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim rngCell As Range Dim lngLstRow As Long lngLstRow = Sheet1.UsedRange.Rows.Count
For Each rngCell In Sheet1.Range("A1:A" & lngLstRow)
If CountIf(Range("A:A"),A1) > 2 Then
MsgBox "Please enter unique value " & rngCell.Address
rngCell.Select
End If
Next
End Sub
答案1
通过使用该Change
事件,我们可以捕获重复的条目而无需进行数据验证:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim RangeOfInterest As Range, Intersection As Range, cell As Range
Set RangeOfInterest = Range("A:A")
Set Intersection = Intersect(RangeOfInterest, Target)
If Intersection Is Nothing Then Exit Sub
With Application
For Each cell In Intersection
If .WorksheetFunction.CountIf(RangeOfInterest, cell.Value) > 1 Then
.EnableEvents = False
.Undo
.EnableEvents = True
MsgBox "duplicates not allowed"
Exit Sub
End If
Next cell
End With
End Sub
笔记:
- 代码可以处理列中的输入内容A以及复制/粘贴到列中
- 该代码可以处理多单元格复制/粘贴到列中