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

时间:2018-04-23 09:08:55

标签: excel vba excel-vba

我正在尝试将固定日期格式添加到我的Excel工作表中,并在VBA代码下面使用日期列B.它工作得很好但我仍然需要在另一列中完全像这样(让我们说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

2 个答案:

答案 0 :(得分:1)

我认为你需要这个:

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

答案 1 :(得分:0)

这比我认为的联盟更简单

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