我的代码如下
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上,我觉得这很奇怪?
我一直在谷歌上试图找到解决方案,大多数人认为这是由从按钮运行动态验证代码引起的,尽管有 Activate 调用,但该按钮仍然聚焦,但我正在运行工作表更改事件而不是按下按钮,所以我认为这不是我的问题 - 有什么想法吗? 我基本上浪费了一整天的时间!:(
如果不从工作表事件运行代码,则代码会很好。对我来说,当您尝试从事件过程中选择新单元格时,就会出现问题。我重写了您的代码在没有选择其他单元格的情况下尝试执行的操作。
试试这个:
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
不是列表的有效定义名称。