2016-04-27 69 views
0

我想限制用户输入一个ID的12位数值。 我正在使用下面的宏;Excel验证多个值粘贴

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 

这项工作成功的逐一价值。如果我复制并尝试粘贴“1234”,则不起作用。但是,如果我复制粘贴批量即多行。然后它全部中断并且验证不起作用。 请建议。

感谢, 希德

+2

为什么不使用数据验证? –

+1

第二次数据验证,但如果你有多个单元格被选中,那么你的目标是一个多个单元格的范围,所以你不能直接使用target.value,你需要使用类似'for each c in target'和check在逐个细胞的基础上。或者使用数组公式来检查字符串的最大和最小长度[参见示例](http://stackoverflow.com/questions/23678242/how-can-i-get-the-length-of-the-longest-string -in-A-列Excel文件) – gtwebb

回答

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