3

我的代码如下

If Cells(Target.Row, 2) = "" And (Cells(Target.Row, 3) = "" Or Cells(Target.Row, 3) = "") Then
    Sheets("MySheet").Activate
    Cells(Target.Row, 3).Activate
    ActiveCell.Validation.Delete
    If (Cells(Target.Row, 2) = "Type A") Then
        ActiveCell.Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=AvailableVersions"
    ElseIf (Cells(Target.Row, 2) = "Type B") Then
        ActiveCell.Validation.Delete
    Else
        ActiveCell.Validation.Add Type:=xlValidateWholeNumber, AlertStyle:=xlValidAlertInformation, Formula1:="0", Formula2:="9999999"
    End If
End If

所以每当我到达 ActiveCell.Validation.Add 时,我遇到的问题就会出现

Run Time Error '1004': Application-defined or object-defined error

这不是一个非常有用的错误,而且数字和列表验证类型也会发生这种情况,所以我确信这不是列表本身的问题,它无论如何都具有工作簿级别的范围。它永远不会发生在我觉得奇怪的 ActiveCell.Validation.Delete 上?

我一直在谷歌试图找到一个解决方案,大多数人认为这是由于从一个按钮运行动态验证代码引起的,尽管激活调用,但我正在运行工作表更改事件而不是按钮按下所以我不要认为这是我的问题 - 有什么想法吗?我基本上浪费了一整天的时间!:(

4

1 回答 1

2

如果您不是从工作表事件中运行它,您的代码会很好。对我来说,当您尝试从事件过程中选择一个新单元格时会出现问题。我重写了您的代码在不选择其他单元格的情况下尝试执行的操作。

尝试这个:

If Cells(Target.Row, 2) = "" And (Cells(Target.Row, 3) = "" Or Cells(Target.Row, 3) = "") Then
    With Sheets("MySheet")
        .Cells(Target.Row, 3).Validation.Delete
        If (.Cells(Target.Row, 2) = "Type A") Then
            .Cells(Target.Row, 3).Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=AvailableVersions"
        ElseIf (.Cells(Target.Row, 2) = "Type B") Then
            .Cells(Target.Row, 3).Validation.Delete
        Else
            .Cells(Target.Row, 3).Validation.Add Type:=xlValidateWholeNumber, AlertStyle:=xlValidAlertInformation, Formula1:="0", Formula2:="9999999"
        End If
    End With
End If

另一个可能的错误是如果AvailableVersions不是列表的有效定义名称。

于 2012-12-06T17:01:49.380 回答