VBA日期:无法获取格式正确

时间:2016-07-14 14:34:34

标签: excel vba date format

我试图将日期从月/日/年转换为完全拼写,如2014年5月31日。

我遇到了障碍。目前,我正在使用此功能,当弹出消息框时,如果有正确的日期(2014年5月31日),但是一旦我将其写入单元格,它就会转换为数字(从5/31 / 14至41790)。我迷失了,并希望得到一些帮助。谢谢!

Dim whatever as String
whatever = Format("5/31/14","mmmm dd, yyyy")
MsgBox whatever
ActiveWorkbook.Activesheet.Cells(1,1) = whatever

我有一个程序使用工作表中的数据来运行邮件合并,所以我试图写出整个日期,而不仅仅是格式化单元格,因为Word获取原始数据(据我所知。)

2 个答案:

答案 0 :(得分:2)

当您尝试在单元格中显示格式时,正确的方法是更改​​单元格的数字格式,然后设置单元格的值

e.g。

Cells(1,1).NumberFormat="MMM DD, YYYY"
Cells(1,1).Value2= Date

答案 1 :(得分:1)

要以序数格式获取日期,请考虑:

Public Function OrdinalDate(d As Date) As String
    Dim dy As Long, mnth As String, yr As Long
    Dim s As String
    ar = Array("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")

    dy = Day(d)
    mnth = MonthName(Month(d))
    yr = Year(d)

    If dy > 10 And dy < 20 Then
        s = "th"
    Else
        s = ar(dy Mod 10)
    End If

    OrdinalDate = dy & s & " " & mnth & " " & yr
End Function

enter image description here

当然删除序号不需要 VBA 。使用 B1 中的序数形式,使用:

=DATEVALUE(SUBSTITUTE(B1,MID(B1,FIND(" ",B1)-2,2),""))

enter image description here

我们回到了我们开始的地方。