【发布时间】:2016-07-21 10:59:18
【问题描述】:
我有 VBA 代码将 6 位数字转换为带有斜杠的日期,即 311215 变为 31/12/2015,但我也希望用户也能够输入带有斜杠的日期。
使用下面的代码,31/12/15 变为 23/04/1969,01/01/15 变为 20/04/2005(?? - 明信片上的答案)。
Private Sub worksheet_change(ByVal target As Range)
Dim StrVal As String
Dim dDate As Date
If target.Cells.Count > 1 Then Exit Sub
If Intersect(target, Range("D7")) Is Nothing Then Exit Sub
With target
StrVal = Format(.Text, "000000")
If IsNumeric(StrVal) And Len(StrVal) = 6 Then
Application.EnableEvents = False
If Application.International(xlDateOrder) = 1 Then 'dd/mm/yy
dDate = DateValue(Left(StrVal, 2) & "/" & Mid(StrVal, 3, 2) & "/" & Right(StrVal, 2))
Else 'mm/dd/yy
dDate = DateValue(Mid(StrVal, 3, 2) & "/" & Left(StrVal, 2) & "/" & Right(StrVal, 2))
End If
.NumberFormat = "dd/mm/yyyy"
.Value = CDate(DateSerial(Year(dDate), Month(dDate), Day(dDate)))
End If
End With
Application.EnableEvents = True
End Sub
我还需要包含验证,以便在单元格中只输入一个日期,因为这在许多其他子项中使用
【问题讨论】: