在 VBA 中将日期转换为文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36507562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:20:21  来源:igfitidea点击:

Converting a date to text in VBA

excelvbaexcel-vba

提问by VBA Pete

I have a data set that includes values as text such as "March 2016".

我有一个数据集,其中包含文本形式的值,例如“2016 年 3 月”。

Now I have written the following code to replicate this in my report sheet:

现在我编写了以下代码来在我的报告表中复制它:

DataFin.Range("E9:E9") = DateSerial(Year(Date), Month(Date), 0)
DataFin.Range("E9:E9").Text = Format(DateSerial(Year(Date), Month(Date), 0), "mmmm yyyy")

It has the correct format, but when I click on the cell the value states "3/1/2016" instead of "March 2016".

它具有正确的格式,但是当我单击单元格时,该值会显示“3/1/2016”而不是“2016 年 3 月”。

Any ideas how I can change the underlying value to "March 2016"

任何想法如何将基础值更改为“2016 年 3 月”

Thanks,

谢谢,

Pete

皮特

回答by Ron Rosenfeld

You must format the cell as text, and then set the value to the text value of the date you want.

您必须将单元格格式化为文本,然后将该值设置为所需日期的文本值。

For example:

例如:

Sub demo()
    Dim DT As Date
DT = Date

With Range("a1")
    .NumberFormat = "@"
    .Value = Format(DT, "mmmm yyyy")
End With
End Sub