【问题标题】:VBA Dates: Cannot Get the Format CorrectVBA 日期:无法正确获取格式
【发布时间】:2016-11-17 12:56:59
【问题描述】:

我正在尝试将日期从诸如月/日/年之类的日期转换为完全拼写出来的日期,例如 2014 年 5 月 31 日。

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

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

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

【问题讨论】:

  • 应用于实际单元格时使用Format
  • 查看MONTHNAME 函数,然后将值直接写入单元格...类似于whatever = Monthname(myDate) & " " & Day(myDate) & ", " & Year(myDate)
  • 在将数据放入之前添加ActiveWorkbook.ActiveSheet.Cells(1,1).NumberFormat = "@"
  • 我使用了 Scott 你的方法。有效!非常感谢:D 你们真的

标签: excel vba date format


【解决方案1】:

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

例如

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

【讨论】:

  • 您可以在 Excel 中设置之前或之后的格式,这没有区别,因为无论如何您都在格式化显示值 - 而不是单元格的值。除此之外 - 这是 OP 想要做的正确答案。
  • 是吗? OP 的示例所需日期格式是 2014 年 5 月 31 日 - IIRC,这将给出 2014 年 5 月 31 日?愿意承认我可能错了!
【解决方案2】:

要获得序数格式的日期,请考虑:

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

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

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

我们又回到了起点。

【讨论】:

    猜你喜欢
    • 2012-07-02
    • 1970-01-01
    • 2016-05-11
    • 2017-04-10
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2014-06-28
    相关资源
    最近更新 更多