VBA 中的格式(SomeDate,"MM/dd") = "12-15"
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8527723/
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
Format(SomeDate,"MM/dd") = "12-15" in VBA
提问by Drew Chapin
I'm writing a VBA macro in Excel that analyzes data from the spreadsheet and sends an email. In this macro, I have to attach the date formatted as "MM/dd" but the output is in the format of "MM-dd". So the question is, why is my slash getting replaced with a dash?
我正在 Excel 中编写一个 VBA 宏,用于分析电子表格中的数据并发送电子邮件。在这个宏中,我必须附加格式为“MM/dd”的日期,但输出格式为“MM-dd”。所以问题是,为什么我的斜线被破折号取代了?
For simplicity, I have reduced the code to this example, and verified the problem exists with this example as well...
为简单起见,我将代码简化为此示例,并验证此示例也存在问题...
Private Sub Test()
Dim Yesterday As Date: Yesterday = DateAdd("d", -1, Now)
MsgBox Format(Yesterday, "MM/dd")
End Sub
When run, the message box shows "12-15" instead of "12/15" as expected.
运行时,消息框按预期显示“12-15”而不是“12/15”。
回答by Jon Skeet
I haven't used VBA myself, but I suspectit's treating /
as "the current culture's date separator" - and you're presumably executing in a culture which uses -
as the date separator. You could try quotingescaping the slash if you definitely alwayswant a slash:
我自己没有使用过 VBA,但我怀疑它被/
视为“当前文化的日期分隔符” - 并且您可能在-
用作日期分隔符的文化中执行。如果您肯定总是想要斜线,则可以尝试引用转义斜线:
MsgBox Format(Yesterday, "MM\/dd")
That's a bit of a guess at both the cause and the fix, but it's at least worth a try.
这对原因和解决方法都有些猜测,但至少值得一试。
EDIT: Thanks to GSerg for the correction of how to perform the right escaping in this context.
编辑:感谢 GSerg 更正了如何在这种情况下执行正确的转义。
回答by aevanko
This has to do with your culture settings in Windows. Go to Control Panel - Regional and Language Options - Customize Regional Options - Date seperator. It's set to "-". If you prefer "/" you can change it there.
这与您在 Windows 中的文化设置有关。转到控制面板 - 区域和语言选项 - 自定义区域选项 - 日期分隔符。它设置为“-”。如果你更喜欢“/”,你可以在那里改变它。
If you wish to format the date regardless of your default regional settings, you can do what Jon Skeet has said (escape the character).
如果您希望格式化日期而不管您的默认区域设置如何,您可以按照 Jon Skeet 所说的进行(转义字符)。