我有一个来自系统的生成文件,此文件的日期格式如下Mar 28 2016 4:55:54:380PM
我在VBA中的脚本没有将此识别为日期或者更确切地说Excel不会将其识别为日期格式,但只有一个字符串。还有其他方法吗?
答案 0 :(得分:2)
这是一个2行代码;)
我假设范围来自A1:A20
。请修改适用
Sub Sample()
[A1:A20].NumberFormat = "DD/MM/YYYY"
[A1:A20] = [index(DATE(MID(A1:A20,8,4),MONTH(1&LEFT(A1:A20,3)),MID(A1:A20,5,2)),)]
End Sub
如果您想了解此代码的作用,请参阅我给出的解释Here
答案 1 :(得分:1)
试试这个
Public Function stringtodate(mytext) As Date
str1 = Split(mytext, " ")
str2 = UBound(str1)
If str2 > 2 Then
If LCase(Left(str1(0), 3)) = "mar" Then
mon = "03"
End If
stringtodate = str1(1) & "-" & mon & "-" & str1(2)
Else
'not a valid date
End If
End Function
答案 2 :(得分:1)
您在评论中提到您只需要日期:
Sub dateTest()
Dim d As Date
s = "Mar 28 2016 4:55:54:380PM"
s = Left(s, 11)
d = DateSerial(Year(s), Month(s), Day(s))
Debug.Print d
End Sub
28.03.2016
迭代某些数据集:
Sub dateIteration()
Dim d As Date, v As Variant
Dim rng As Range
Set rng = Range("A1:A10")
For Each r In rng
v = Left(r.Value, 11)
d = DateSerial(Year(v), Month(v), Day(v))
' Do something with d
' Print it to worksheet, maybe?
r.Value = d
Next r
End Sub
使用最少的代码杂乱迭代非连续范围:
Sub helperSub()
Call dateIteration(Range("A1:A10"))
Call dateIteration(Range("Z1:Z10"))
Call dateIteration(Range("H1:M89"))
End Sub
Sub dateIteration(rng As Range)
Dim d As Date, v As Variant
For Each r In rng
v = Left(r.Value, 11)
d = DateSerial(Year(v), Month(v), Day(v))
' Do something with d
' Print it to worksheet, maybe?
r.Value = d
Next r
End Sub
答案 3 :(得分:0)
VBA中的日期格式不是#MM / DD / YYYY h:mm:ss.sss PM#?