避免在Excel中出现多个错误popup消息
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列应用validation,即使validation通过我得到4错误popup消息如何限制错误消息的数量?
更新:
我从下拉菜单中select了一个有效的select,但是我收到了下面的错误消息。 我正在使用下面的代码
如果你正在处理表单的Change
事件,那么我build议你看看这个
由于您只使用一张工作表,因此您不需要在ThisWorkbook
代码区中input代码。 如果你把它放在那里,那么代码将运行每个工作表。 将代码放在相关工作表的代码区域。 所以如果validation是在Sheet1
然后将代码放在Sheet1
代码区域。 请参阅下面的ScreenShot。
好吧,现在解决您的查询。 你可以做的是使用Boolean
variables,然后在显示第一条消息之后将其设置为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