避免在Excel中出现多个错误弹出消息

时间:2013-09-24 08:59:05

标签: excel excel-vba vba

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条错误弹出消息,如何限制错误消息的数量?

更新

我从下拉列表中选择了一个有效选择的值,但是我收到以下错误消息。 My sample excel我使用以下代码

1 个答案:

答案 0 :(得分:1)

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

由于您只使用一张工作表,因此您不需要ThisWorkbook代码区域中的代码。如果你把它放在那里,那么每个工作表都会运行代码。将代码放在相关表单的代码区域中。因此,如果验证位于Sheet1,则将代码放在Sheet1代码区域中。见下面的ScreenShot。

enter image description here

现在好了解决你的问题。您可以执行的操作是使用Boolean变量,然后在显示第一条消息后将其设置为True,以便不再显示该消息。

试试这个(UNTESTED)

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