尝试将某些格式转换为日期格式

时间:2015-05-01 10:24:44

标签: excel vba date-format

我已经能够获得以下代码来成功转换一般值" 19082015"和" 9052015"进入日期格式dd / mm / yyyy。

但是当我尝试转换一般价值" 19.08.2015"在相同的代码中,它不运行宏并显示:

运行时错误' 13': 输入错误匹配

在线" l =范围(" A1")。值"

需要做什么才能处理" 19.08.2015"格式呢?

Sub convertdate()

Dim l As Long
Dim testdate As String
Dim convertdate As Date

l = Range("A1").Value

testdate = CStr(l)

dotdate = False
If InStr(testdate, ".") Then dotdate = True
If dotdate = False Then convertdate = DateValue(CInt(Left(testdate, Len(testdate) - 6)) & "/" & CInt(Mid(testdate, Len(testdate) - 5, 2)) & "/" & CInt(Right(testdate, 4)))
If dotdate = True Then convertdate = DateValue(CInt(Left(testdate, Len(testdate) - 8)) & "/" & CInt(Mid(testdate, Len(testdate) - 6, 2)) & "/" & CInt(Right(testdate, 4)))

Range("A2").Value = convertdate

End Sub

2 个答案:

答案 0 :(得分:2)

问题是如果Range("A1")不是数字。因此,如果它中有.,那么您就不能将该值放入long中。将l声明为string而非long,您的代码将起作用

答案 1 :(得分:0)

[a2] = CDate(Join(Split([a1], "."), "-"))