强制粘贴值以遵守数据validation规则

我有一个(简单的例子)由input和报警组成的matrix。 每个动作(X)应该有一个input和一个警报,即不应该在列E或列6中插入动作。

我使用数据validation来实现这一点,它的工作原理。

但是,如果我将数据粘贴到这些单元格,则不会遵循validation规则。 我插入这个VBA代码,以防止这(从www.j-walk.com/ss/excel/tips/tip98.htm提取):

Private Sub Worksheet_Change(ByVal Target As Range) 'Does the validation range still have validation? If HasValidation(Range("ValidationRange")) Then Exit Sub Else Application.EnableEvents = False Application.Undo MsgBox "Your last operation was canceled." & _ " It would have deleted data validation rules.", vbCritical End If End Sub Private 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 

然而,这个代码还可以防止粘贴到单元格中的值,即使它们没有违反validation规则,例如,如果我粘贴一个X来input;警报1,我会收到一条错误消息。 有没有办法阻止只有当他们违反validation规则时粘贴的值?

编辑:

我已经改变了代码:

 Private Sub Worksheet_Change(ByVal Target As Range) With Range("D4:H8").Validation .Delete .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Operator:= _ xlBetween, Formula1:="=OR(ISBLANK(D4),AND(NOT(ISBLANK($C4)),NOT(ISBLANK(D$3))))" .IgnoreBlank = False .InCellDropdown = True .InputTitle = "" .ErrorTitle = "Stop" .InputMessage = "" .ErrorMessage = "Actions Must Have Input and Output" .ShowInput = True .ShowError = True End With Me.CircleInvalid Count = 0 Dim shp As Shape For Each shp In ActiveSheet.Shapes If Not Intersect(shp.TopLeftCell, Range("D4:H8")) Is Nothing Then Count = Count + 1 Next If Count > 0 Then MsgBox "Actions Must Have Input and Output" End If End Sub 

这现在圈出无效的单元格,并产生一个信息框,如果find了。 这是基于无效圆是形状的事实完成的。 我可以通过search整个工作表来获得代码工作,但我试图缩小search到指定的范围。 但是,由于shp.TopLeftCell,我得到错误“1004 – 应用程序定义或对象定义的错误”。 有任何想法吗?

决定不要去形状路线,而是searchvalidation值:

 Dim Cell As Range For Each Cell In Range("D4:H8") If Not Cell.Validation.Value Then MsgBox "Actions Should Have Input and Output" Exit Sub End If Next 

尝试做一个特殊的粘贴; 普通的粘贴覆盖单元格的格式属性。

单击单元格并点击粘贴,然后单击该单元格并将数据粘贴到Excel顶部的公式栏中。 然后按回车。 这使我可以从剪贴板粘贴文本,但保留数据validation。

我只用excel和外部来源的文本和数字进行testing,从来没有使用高级公式等,所以它可能无法满足所有需求。

这是每贴一个额外的步骤,但它节省了我在一个特定的项目,我需要检查字符计数大量的时间。