2017-10-20 21 views
0

我有一個代碼在所選列中輸入唯一日期。但是我只想在(U和X)的兩個欄中應用。任何人都可以請幫助我如何可以包括其他列僅允許多列中的日期格式

Private Sub Worksheet_Change(ByVal Target As Range) 

    Set r = ActiveSheet.Range("B2:B20000") 
    For Each c In r 

     If c.Value <> "" And Not IsDate(c) Then 
      c.ClearContents 
      MsgBox "Please enter only date in this format DD/MM/YYYY " 
     End If 

    Next c 

End Sub 

回答

0

我有一個替代的解決方案創建一個Sub,並要求從Worksheet_Change事件子。您可以多次調用Sub,指出需要驗證的列。

Private Sub Worksheet_Change(ByVal Target As Range) 

    Call ValidateDate(2) 'For Column B 
    Call ValidateDate(8) 'For Column H 

End Sub 


Private Sub ValidateDate(Col As Integer) 

    Set r = ActiveSheet.Range(Cells(1, Col), Cells(20000, Col)) 
    For Each c In r 
     If c.Value <> "" And Not IsDate(c) Then 
      c.ClearContents 
      MsgBox "Please enter only date in this format DD/MM/YYYY " 
     End If 
    Next c 

End Sub 
+0

沒有'Application.EnableEvents'這可能會導致excel崩潰,並且每次調用c.ClearContents時它都會一次又一次地觸發ontop本身。 –

0

首先,對此沒有必要使用VBA。您可以在所需的單元上使用Data Validation

但是,如果你絕對想要VBA,這是一種你可以包含其他列的方法,並且確保代碼只關心你關心的單元格之一是否發生了變化。

Option Explicit 

Private Sub Worksheet_Change(ByVal Target As Range) 

    Dim TestRange As Range 

    Set TestRange = Me.Range("B2:B20000") 
    Set TestRange = Union(TestRange, Me.Range("U2:U20000")) 
    Set TestRange = Union(TestRange, Me.Range("U2:X20000")) 

    If Not Intersect(Target, TestRange) Then 

     Dim CheckCell As Range 

     For Each CheckCell In TestRange 

      If CheckCell.Value <> "" And Not IsDate(CheckCell) Then 

       Application.EnableEvents = False 
       CheckCell.ClearContents 
       Application.EnableEvents = True 
       MsgBox "Please enter only date in this format DD/MM/YYYY " 

      End If 

     Next 

    End If 

End Sub