Excel VBA:可以删除validation,但不能添加新的validation

我的代码如下

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 

不是一个非常有用的错误,而且这也发生在数字和列表validationtypes,所以我相信它不是一个问题,无论如何这个列表本身有工作簿级别的作用域。 它从来没有发生ActiveCell.Validation.Delete我觉得奇怪?

我一直在谷歌试图find一个解决scheme,大多数人build议,这是由运行dynamicvalidation代码从一个button,尽pipe激活呼吁,但我运行在换单事件,而不是在buttonbutton,因此我不要以为这是我的问题 – 任何想法? 我基本上浪费了一整天的时间! 🙁

如果你没有从工作表事件中运行它,你的代码将会很好。 对于我来说,当你尝试从事件过程中select一个新的单元格时,就会出现这个问题。 我重写了它看起来像你的代码试图做,而不select一个不同的单元格。

尝试这个:

 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不是一个有效的列表定义名称。