Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

excel - Format(SomeDate,"MM/dd") = "12-15" in VBA

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I haven't used VBA myself, but I suspect it'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 quoting escaping the slash if you definitely always want a slash:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...