1
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("A1:A1048576")) Then RestoreValidation
    If Not HasValidation(Range("C1:C1048576")) Then RestoreValidation
    If Not HasValidation(Range("I1:I1048576")) Then RestoreValidation
    If Not HasValidation(Range("P1:P1048576")) 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

我使用上面的代码对 4 列应用了验证,即使验证通过了,我也收到 4 条错误弹出消息,如何限制错误消息的数量?

更新:

我从下拉列表中选择了有效选择的值,但我收到以下错误消息。 我的样本excel我正在使用以下代码

4

1 回答 1

1

如果您正在处理工作表的Change事件,那么我建议您看看THIS

由于您只使用一张纸,因此您不需要ThisWorkbook代码区域中的代码。如果你把它放在那里,那么代码将为每张纸运行。将代码放在相关工作表的代码区域。所以如果验证是在Sheet1然后把代码放在Sheet1代码区域。请参阅下面的屏幕截图。

在此处输入图像描述

好的,现在解决您的问题。您可以做的是使用一个Boolean变量,然后True在显示第一条消息后将其设置为,这样该消息就不会再次显示。

试试这个(未经测试)

Dim boolDontShowAgain As Boolean

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    Application.EnableEvents = False

    If Not HasValidation(Range("A1:A1048576")) Then RestoreValidation
    If Not HasValidation(Range("C1:C1048576")) Then RestoreValidation
    If Not HasValidation(Range("I1:I1048576")) Then RestoreValidation
    If Not HasValidation(Range("P1:P1048576")) Then RestoreValidation

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

Private Sub RestoreValidation()
    Application.Undo
    If boolDontShowAgain = False Then
        MsgBox "Your last operation was canceled." & _
        "It would have deleted data validation rules.", vbCritical
        boolDontShowAgain = True
    End If
End Sub

Private Function HasValidation(r) As Boolean
    On Error Resume Next
    Debug.Print r.Validation.Type
    If Err.Number = 0 Then HasValidation = True
End Function
于 2013-09-24T09:53:34.907 回答