excelinput带或不带斜杠的date
我有VBA代码将一个6位数的数字转换成斜杠的date,即311215变成2015年12月31日,但我也希望用户能够input一个斜线的date。
使用下面的代码,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
我还需要包含validation,以便在单元格中只input一个date,因为这在其他许多子目录中都有使用
您的string31/12/15
被计算为date,并通过Format(.Text, "000000")
转换为内部整数表示42369
(这是1900年以来的天数)。 您的Format
命令不会删除斜杠,而是将值解释为整数string。 之后,你的代码将这个数字转换为23/04/1969
。
你可以尝试replace你的
StrVal = Format(.Text, "000000")
通过
StrVal = Replace(.Text, "/", "")
。
此代码假定在任何用户input之前 D7已被格式化为文本 :
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 Application.EnableEvents = False With target StrVal = .Text If IsNumeric(StrVal) And Len(StrVal) = 6 Then 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 = dDate Else ary = Split(StrVal, "/") If Len(ary(2)) = 2 Then ary(2) = "20" & ary(2) 'fix the year if necessary If Application.International(xlDateOrder) = 1 Then 'dd/mm/yy dDate = DateValue(ary(2) & "/" & ary(1) & "/" & ary(0)) Else 'mm/dd/yy dDate = DateValue(ary(2) & "/" & ary(0) & "/" & ary(1)) End If .NumberFormat = "dd/mm/yyyy" .Value = dDate End If End With Application.EnableEvents = True End Sub