如何将 VBA 文本框格式化为长日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13420691/
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
How to Format VBA TextBox To Long Date
提问by user1760110
I have a textbox for date display which shows the date in this format: 17/04/2012 but I would like to format it to shows up like 'April 17, 2012'. I tried this code
我有一个用于日期显示的文本框,它以这种格式显示日期:17/04/2012,但我想将其格式化为“2012 年 4 月 17 日”。我试过这个代码
UserForm1.txtDate = Format(Long Date)
which I am getting syntax error from compiler.Can you please let me know how I can do it? Thanks
我从编译器那里收到语法错误。你能告诉我我该怎么做吗?谢谢
回答by bonCodigo
there have been couple of posts on this. Culprit seems to be your system date format. Use of short, medium, long formats will change the result when the system settings change.
有几个帖子关于这个。罪魁祸首似乎是您的系统日期格式。当系统设置改变时,短、中、长格式的使用将改变结果。
- In US systems mainly it's done as, e.g.
Format$(yourdate, “dd/mm/yyyy”)
- Where as European systems, e.g.
Format$(yourdate, “short date”)
- 在美国系统中,主要是这样做的,例如
Format$(yourdate, “dd/mm/yyyy”)
- 作为欧洲系统,例如
Format$(yourdate, “short date”)
If we look at explicitly defining your format, you are formulating your regional settings!
如果我们查看明确定义您的格式,您正在制定您的区域设置!
Good e.g. short date won't always be mm/dd/yyyy but could be dd/mm/yyyy.That's the key advantage over actually specifying the format. Simply you can change how you want your date to look like instead of depending on the system (with or without your knowledge).
好的,例如短日期并不总是 mm/dd/yyyy,但可能是 dd/mm/yyyy。这是与实际指定格式相比的主要优势。只需更改您希望日期的外观,而不是取决于系统(无论您是否知情)。
When we first encountered this, we had some making the VBA apps and sending it over to another in some other place where they have own localized system date format. Your phone rings... ;)
当我们第一次遇到这种情况时,我们有一些制作 VBA 应用程序并将其发送到其他地方的另一个地方,他们有自己的本地化系统日期格式。你的电话响了……;)
- Short/Long Date: Display a date according to your system's long date format.
- Medium Date: Display a date using the medium date format appropriate for the language version of the host application.
- 短/长日期:根据系统的长日期格式显示日期。
- 中日期:使用适合主机应用程序语言版本的中日期格式显示日期。
In your case you could use,
在你的情况下,你可以使用,
UserForm1.txtDate.Value = Format$(Date,"mmmm dd, yyyy")
Or to be super-safe,
或者为了超级安全,
Dim dtDate as Date
dtDate = DateSerial(Year(Date), Month(Date), Day(Date))
UserForm1.txtDate.Value = Format$(dtDate, "mmmm dd, yyyy")
Hope that helps.
希望有帮助。