我有一个工作表,我已经阻止用户将普通列中的单元格复制并粘贴到具有数据验证下拉列的列中的另一个单元格中。
我现在遇到的问题是,用户能够将具有数据验证的列中的单元格复制并粘贴到具有数据验证的列中的另一个单元格中。有什么方法可以阻止这个吗?
非常感谢, 基兰
答案 0 :(得分:1)
您可以在更改后检查单元格是否仍有验证。
使用Workbook更改事件,在ThisWorkbook模块中
Option Explicit
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'Does the validation range still have validation?
If Not HasValidation(Range("RangeToProtect1")) Then RestoreValidation
If Not HasValidation(Range("RangeToProtect2")) Then RestoreValidation
If Not HasValidation(Range("RangeToProtect3")) Then RestoreValidation
If Not HasValidation(Range("RangeToProtect4")) Then RestoreValidation
End Sub
Private Sub RestoreValidation()
Application.EnableEvents = False
'turn off events so this routine is not continuously fired
Application.Undo
Application.EnableEvents = True
'and turn them on again so we can catch the change next time
MsgBox "Your last operation was canceled." & _
"It would have deleted data validation rules.", vbCritical
End Sub
Private Function HasValidation(r) As Boolean
' Returns True if every cell in Range r uses Data Validation
On Error Resume Next
Debug.Print r.Validation.Type 'don't care about result, just possible error
If Err.Number = 0 Then HasValidation = True Else HasValidation = False
End Function
在RangeToProtect
中,您可以指定特定范围,也可以使用命名范围(请注意,命名范围虽然使代码易于阅读,但如果删除整个范围,则会导致代码失败你正试图保护)