Validation.Type抛出错误1004

时间:2014-06-12 17:25:25

标签: validation excel-vba excel-2013 vba excel

我正在尝试根据我在网上找到的代码使用此代码,以防止数据验证被复制并粘贴到已定义数据验证的单元格中:

Private Sub Worksheet_Change(ByVal Target As Range)
'Does the validation range still have validation?
    If HasValidation(Range("D3:D4")) Then
        Exit Sub
    Else
        Application.Undo
        MsgBox "Your last operation was canceled." & _
        "It would have deleted data validation rules.", vbCritical
    End If
End Sub

Function HasValidation(r) As Boolean
'   Returns True if every cell in Range r uses Data Validation
    On Error Resume Next
    x = r.Validation.Type
    If Err.Number = 0 Then HasValidation = True Else HasValidation = False
End Function

但是,它总是触发撤消和错误对话框,即使我尝试编辑不相关的单元格,如果我注释掉On Error Resume Next,我也可以看到该行

x = r.Validation.Type

失败,错误1004。

2 个答案:

答案 0 :(得分:0)

发生这种情况是因为我在一个单元格中更新了数据验证的错误消息,但没有更新。

当我将错误消息复制并粘贴到范围内其他单元格的数据验证中时,此问题就消失了。

结论:确保数据验证的定义方式完全相同,包括错误消息,范围内的所有单元格。

答案 1 :(得分:0)

如果将数据验证范围与不同的规则/列表一起使用,则也需要单独检查它们(不要将不连续的联合验证范围定义为HasValidation函数的输入)-否则也会通过错误1004。 / p>

'Does the validation ranges still have validation? Need to be checked seperately, otherwise error 1004
If HasValidation(Range("ValidationRangeA")) = True And _
HasValidation(Range("ValidationRangeB")) And _
HasValidation(Range("ValidationRangeC")) And _
HasValidation(Range("ValidationRangeD")) Then
         Exit Sub
Else

    Application.EnableEvents = False
        Application.Undo
    Application.EnableEvents = True

    MsgBox "Your last operation was canceled." & _
    "It would have deleted data validation rules.", vbCritical
End If

结束子