我有一个代码可以输入所选列中的唯一日期。但我想在(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 :(得分: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
答案 1 :(得分: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