简体   繁体   English

使用VBA代码更改日期格式

[英]Change date format using VBA Code

I have this code to show the date in the following format like (Date: March 22, 2015) but it shows it as (Date: 3/22/2015) so please assist. 我有这段代码以以下格式显示日期,例如[日期:2015年3月22日],但将其显示为[日期:2015年3月22日],请提供帮助。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim dtmTest As Date
dtmTest = DateValue(Now)
Range("A1") = Format(dtmTest, "mmmm dd, yyyy")
Range("A1") = "Date : " & dtmTest
End Sub

You need to change the cell formatting to text to obtain the desired effect. 您需要将单元格格式更改为文本以获得所需的效果。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Sets cell formatting to string
Range("A4").NumberFormat = "@"
'fills range with formatted date
Range("A4").Value = Format(Now, "mmm, dd yyyy")
End Sub

The solution posted works, but your original code was almost correct. 解决方案发布了,但是您的原始代码几乎是正确的。 You reformatted the date with the format function, but then overwrote it with the dtmtest variable. 您使用格式函数重新格式化了日期,但随后使用dtmtest变量覆盖了日期。 Try this: 尝试这个:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim dtmTest As Date
dtmTest = DateValue(Now)
Range("A1") = "Date : " & Format(dtmTest, "mmmm dd, yyyy")
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM