用户可以像这样自由地在B栏中输入日期:
(英国格式的日期) B栏
02/01/2017
02.01.2017
01.01.17
01012017
010117
当我们想要运行这些日期格式不一致的报告时,它非常令人沮丧。
我正在尝试创建一个格式化日期的代码,但是输入的斜杠是这样的:
02/01/2017
02/01/2017
01/01/2017
01/01/2017
etc...
这是我的代码:
Dim Cell As Range, CellVal As String
If Not Intersect(Target, ActiveSheet.Columns("B")) Is Nothing Then
For Each Cell In Intersect(Target, ActiveSheet.Columns("B"))
CellVal = Cell.Value
If (Not CellVal Like "*[!0-9]*") And (Len(CellVal) > 4) Then
CellVal = Format(CellVal, "@@ @@ @@")
Cell.Value = CDate(WorksheetFunction.Replace(CellVal, 4, 2, MonthName(Mid(CellVal, 4, 2))))
Cell.NumberFormat = "dd/mm/yyyy"
End If
Next Cell
End If
如果用户输入9位数字格式似乎只有这样:
01012017
然后将其更改为
01/01/2017
但如果用户输入
010117
然后转换为:
28/01/1955 <---This is wrong
另一方面,用户可以输入点:
01.01.2017
然后代码根本不起作用。
有人可以告诉我更好的方法吗?
答案 0 :(得分:0)
保持简单明了......不是吗?
Dim Cell As Range, CellVal As String, dim Dt as Date
If Not Intersect(Target, ActiveSheet.Columns("B")) Is Nothing Then
For Each Cell In Intersect(Target, ActiveSheet.Columns("B"))
val = Cell.Value
if instr(val,".")>0 then 'check if this particular char is present
temp = split(val,".")
day= temp(0)
month=temp(1)
year=temp(2)
Dt = DateSerial(year, month, day)
Cell.Value= Format(Dt, "dd/mm/yy") 'you can change this to "dd-mmm-yyyy" or whatever
else if instr(val,"/")>0 then
temp = Split(val,"/")
day= temp(0)
month=temp(1)
year=temp(2)
Dt = DateSerial(year, month, day)
Cell.Value= Format(Dt, "dd/mm/yy")
else if len(val) = 8 then
day = left(val,2) ' start at first, and take 2
month = mid(val, 3,2) 'start a 3rd char and take 2
year = right(val,4)
Dt = DateSerial(year, month, day)
Cell.Value= Format(Dt, "dd/mm/yy")
else if len(val) = 6 then
day = left(val,2) ' start at first, and take 2
month = mid(val, 3,2) 'start a 3rd char and take 2
year = right(val,2)
year = year +2000
Dt = DateSerial(year, month, day)
Cell.Value= Format(Dt, "dd/mm/yy")
end if
Next Cell
End If
我可能在func中犯了一些错误。参数在这里,因为它早上1:30,我没有在我的笔记本电脑上表现出色,但我认为我的主要部分是正确的:)