将日期输入VBA效果放在同一工作表中两个不同区域的单元格中

将日期输入VBA效果放在同一工作表中两个不同区域的单元格中,vba,excel,Vba,Excel,我正在尝试将固定日期格式放入我的Excel工作表中,并在日期列B的VBA代码下面使用。它工作得很好,但我仍然需要在另一列(比如E列)中完全像这样做。但我不知道如何将这种效应应用到另一个范围的细胞上(见E列)。有什么想法和建议吗 Private Sub Worksheet_Change(ByVal Target As Range) Dim DateStr As String On Error GoTo EndMacro If Application.Intersect(Target, Range

我正在尝试将固定日期格式放入我的Excel工作表中,并在日期列B的VBA代码下面使用。它工作得很好,但我仍然需要在另一列(比如E列)中完全像这样做。但我不知道如何将这种效应应用到另一个范围的细胞上(见E列)。有什么想法和建议吗

Private Sub Worksheet_Change(ByVal Target As Range)
Dim DateStr As String

On Error GoTo EndMacro
If Application.Intersect(Target, Range("B4:B1048576")) Is Nothing Then
Exit Sub
End If
If Target.Cells.Count > 1 Then
Exit Sub
End If
If Target.Value = "" Then
Exit Sub
End If

Application.EnableEvents = False
With Target
If .HasFormula = False Then
Select Case Len(.Formula)
    Case 4 ' e.g., 9298 = 2-Sep-1998
        DateStr = Mid(.Formula, 2, 1) & "/" & _
        Left(.Formula, 1) & "/" & Right(.Formula, 2)
    Case 5 ' e.g., 11298 = 12-Jan-1998 NOT 2-Nov-1998
        DateStr = Mid(.Formula, 2, 2) & "/" & _
        Left(.Formula, 1) & "/" & Right(.Formula, 2)
    Case 6 ' e.g., 090298 = 2-Sep-1998
        DateStr = Mid(.Formula, 3, 2) & "/" & _
        Left(.Formula, 2) & "/" & Right(.Formula, 2)
    Case 7 ' e.g., 1231998 = 23-Jan-1998 NOT 3-Dec-1998
        DateStr = Mid(.Formula, 2, 2) & "/" & _
        Left(.Formula, 1) & "/" & Right(.Formula, 4)
    Case 8 ' e.g., 09021998 = 2-Sep-1998
        DateStr = Mid(.Formula, 3, 2) & "/" & _
        Left(.Formula, 2) & "/" & Right(.Formula, 4)
    Case Else
        Err.Raise 0
End Select
.Formula = DateValue(DateStr)
End If

End With
Application.EnableEvents = True
Exit Sub
EndMacro:
MsgBox "You did not enter a valid date."
Application.EnableEvents = True
End Sub
我想你需要这个:

If Application.Intersect(Target, Union(Range("B4:B1048576"),Range("E4:E1048576"))) Is Nothing Then
'rest of your code

这比我想的更简单

If Application.Intersect(Target, Range("D2:D1048576,E2:E1048576,etc...as much 
column names as you want")) Is Nothing Then
Exit Sub
End If

尝试在开始时将
“B4:B1048576”
更改为
“E4:E1048576”
。我认为如果我这样更改,代码将只影响
“E列”
,并将停止处理
“B列”
。你是说?是的。你想同时改变两个颜色吗?是的,我需要这样做。