多个值粘贴的Excel验证

时间:2016-04-27 18:06:52

标签: excel

我试图限制用户为ID输入12位数值。 我正在使用以下宏;

Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Column <> 1 Then GoTo Exit_Sub
    If Len(Target.Value) <> 12 Then
        MsgBox " Plese enter exactly 12 characters!!"
        Application.Undo
    End If
Exit_Sub:
Application.EnableEvents = True
End Sub

这对于逐个值的成功运作是成功的。如果我复制并尝试粘贴&#34; 1234&#34;它没有用。但是如果我在批量中复制粘贴,即多行。然后它全部中断,验证不起作用。 请建议。

谢谢, SID

1 个答案:

答案 0 :(得分:0)

要处理多个单元格,您需要循环:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim r As Range

    Application.EnableEvents = False
    If Target.Column <> 1 Then GoTo Exit_Sub
        For Each r In Target
            If Len(r.Value) <> 12 Then
                MsgBox " Plese enter exactly 12 characters!!"
                r.Value = ""
            End If
        Next r
Exit_Sub:
    Application.EnableEvents = True
End Sub