2016-04-27 70 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